我可以将这3个重写规则合并为1吗?

时间:2016-09-14 23:46:14

标签: .htaccess url-rewriting

我的大脑褪色,需要一些帮助。我使用3个RewriteRules来完成我认为应该只采用一个的东西:

RewriteRule ^([0-9]+)$ /bar/$1.html [R=301,L]
RewriteRule ^([0-9]+)(-*)$ /bar/$1.html [R=301,L]
RewriteRule ^([0-9]+)-([0-9]+)$ /bar/$1.html#$2 [R=301,NE,L]

我需要使用以下网址:

http://foo.com/100
http://foo.com/100-1
http://foo.com/200-
http://foo.com/1999
http://foo.com/1999-99

...并像这样重写它们:

http://foo.com/bar/100.html
http://foo.com/bar/100.html#1
http://foo.com/bar/200.html
http://foo.com/bar/1999.html
http://foo.com/bar/1999.html#99

我的工作但看起来有点像黑客。有没有办法将这一切结合到一个规则中?

2 个答案:

答案 0 :(得分:1)

我没有看到将所有三个规则组合成单个规则的方法,因为替换结构并不总是相同的,哈希有时会出现,有时不会出现。但是你可以结合前两个规则:

RewriteRule ^([0-9]+)-?$ /bar/$1.html [R=301,L]

替换为哈希符号的第二条规则可以保持原样:

RewriteRule ^([0-9]+)-([0-9]+)$ /bar/$1.html#$2 [R=301,NE,L]

答案 1 :(得分:1)

您可以使用此技巧将所有3个规则合并为一个:

RewriteCond %{REQUEST_URI} ^/(\d+)-?(\d+)?$
RewriteCond %1#%2 ^(\d+)#$ [OR]
RewriteCond %1#%2 ^(\d+)(#\d+)$
RewriteRule ^ /bar/%1.html%2 [R=301,L,NE]
  • 在第一个条件中,我们匹配以数字开头的正则表达式模式,后跟可选的连字符和另一个可选数字。
  • 接下来两个条件正在使用[OR],因此只有一个条件成立。
  • 对于URI /100,第一个条件为真,100将在%1中捕获,但%2将为空。
  • 对于URI /100-1,第二个条件为真,100将在%1中捕获,但%2将为#1
相关问题