2017-02-20 113 views
1

我已经遵循各种示例使用mod-rewrite从包含下划线的URL重定向到包含连字符的URL。但它陷入了一个循环,我看不出有什么问题。用.htaccess中的连字符替换下划线但陷入循环

我想重定向的URL,如:

http://www.example.org/blog/archive/2016/12/31/my_post_slug_here.html 

到:

http://www.example.org/blog/2016/12/31/my-post-slug-here/ 

所有这一切是很简单的,除了下划线至连字符。我现在有这在我的.htaccess文件:

RewriteRule ^blog/archives/([0-9]{4}/[0-9]{2}/[0-9]{2})/([^_]*)_([^_]*_.*).html$ blog/archives/$1/$2-$3.html [N] 
RewriteRule ^blog/archives/([0-9]{4}/[0-9]{2}/[0-9]{2})/([^_]*)_([^_]*).html$ /blog/$1/$2-$3/ [R=301,L] 

第二条规则正确重定向,如果我只用包含一个下划线(例如.../my-post-slug_here.html)的URL。但是第一个 - 它应该递归地用连字符代替下划线,直到只剩下一个 - 被卡在一个循环中。我的日志是这样的:

[Mon Feb 20 14:35:47.430250 2017] [rewrite:trace3] [pid 7844] mod_rewrite.c(476): 
[client 192.168.33.1:54128] 192.168.33.1 - - [www.example.dev/sid#7f6f3fcdecc8][rid#7f6f3fbb20a0/initial] 
[perdir /var/www/public/] applying pattern 
'^blog/archives/([0-9]{4}/[0-9]{2}/[0-9]{2})/([^_]*)_([^_]*_.*).html$' to uri 
'blog/archives/2016/12/31/my-post-slug-here.html/archives/2016/12/31/my-post-slug-here.html/archives/2016/12/31/my-post-slug-here.html/archives/2016/12/31/my-post-slug-here.html/archives/2016/12/31/my-post-slug-here.html/archives/2016/12/31/my-post-slug-... 

所以它看起来像它取代了下划线,然后莫名其妙地陷入...

回答

1

你的规则几乎是正确的。问题是Apache将原始路径信息附加到重写的URI并且它将陷入无限循环(由于标记为N)。

您需要添加DPI flag (Discard Path)N才能停止此行为。

后重构你的规则可以点点:

# redirect when we have only one underscore in URI 
RewriteRule ^blog/archives/(\d{4}/\d{2}/\d{2})/([^_]*)_([^_]*)\.html$ /blog/$1/$2-$3/ [R=301,NC,NE,L] 

# otherwise keep replacing underscore with hyphen in a loop 
RewriteRule ^(blog/archives/\d{4}/\d{2}/\d{2})/([^_]*)_([^_]*_.*\.html)$ $1/$2-$3 [N,NC,DPI] 
+1

哇,非常感谢anubhava!它第一次运作!我试图遵循的例子并没有那样,但在这里肯定有不同。感谢重构 - 现在有点整洁:) –

0

不知道这是否有差别,但也许尝试使规则的目标绝对的,由

RewriteRule ^blog/archives/([0-9]{4}/[0-9]{2}/[0-9]{2})/([^_]*)_([^_]*_.*).html$ /blog/archives/$1/$2-$3.html [N] 

另一件事你也许可以尝试被重定向时,有没有更多的下划线:

RewriteCond %{THE_REQUEST} blog/archives/[0-9]{4}/[0-9]{2}/[0-9]{2)/[^\ \?]*_ 
RewriteRule ^blog/archives/([0-9]{4}/[0-9]{2}/[0-9]{2})/([^_]+).html$ /blog/$1/$2/ [R=301,L] 

RewriteRule ^blog/archives/([0-9]{4}/[0-9]{2}/[0-9]{2})/([^_]*)_(.*).html$ /blog/$1/$2-$3.html [L] 
01在前面加一个
+0

感谢乔恩 - 我会尝试的第一个想法,并没有奏效。 anubhava的解决方案似乎有诀窍。 –