htaccess 使用正则表达式和无限重定向重写规则

htaccess rewrite rules with regexp and inifite redirect

我很难使用 WP 的旧 URL 的一部分为重定向创建重写规则。示例:

旧URL:

http://www.example.com/news/index.php/2014/11/07/my-blog-post-from-old-site

http://www.example.com/news/index.php/2014/11/07/my_blog_post_from_old_site

新 URL:

http://www.example.com/2014/11/07/my-blog-post

新的 URL 在从破折号中剥离后应该只有日期和永久链接的前三个元素。

我的解决方案是结合此处 and here

的答案得出的

以某种方式用破折号替换下划线的部分创建无限重定向和服务器冻结。如果我将删除部分,将下划线替换为破折号,则所有其余部分都可以正常工作。

这是我的 .httaccess 规则

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#replace underscores with dashes
RewriteRule ^(/news/.*/[^/]*?)_([^/]*?_[^/]*)$ - [N]
RewriteRule ^(/news/.*/[^/]*?)_([^/_]*)$ - [R=301,L,NC]

#redirect to new URL
RewriteRule ^news/index\.php/([^-]+-[^-]+-[^-]+).* / [R=301,L,NC]

#WP standard stuff
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

我认为,这是一种用破折号替换下划线的昂贵方法。但这至少在我的测试环境中有效。第一条规则逐个替换破折号。第二条规则然后从请求的 URL.

中删除前缀
RewriteBase /

# replace underscores with dashes 
RewriteRule ^(news/index.php/.+?)_(.*) - [L]

# strip "news/index.php"
RewriteRule ^news/index.php/(.*) / [R=302,L]

我使用 N|next 标志对您的原始方法进行了更多尝试,结果我的服务器也崩溃了。查看 error.log,这个无限循环似乎是由 Apache 通过添加 "path info postfix" 创建的,它用原来的 URL 扩大了 URL。因此它不断地用破折号替换下划线。

您可以使用另一个标志 DPI|discardpath 来阻止此 路径信息后缀 ,它给出了以下规则

RewriteRule ^(news/index.php/.+?)_(.*) - [N,DPI]

这似乎也有效。虽然我必须承认,我并不真正理解这个 "path info postfix" 东西。 Apache 的 Bugzilla 中也有一个条目,Bug 38642: mod_rewrite adds path info postfix after a substitution occured


切勿在启用 301 的情况下进行测试,有关详细信息,请参阅此答案 Tips for debugging .htaccess rewrite rules