【问题标题】:htaccess rewrite rules with regexp and inifite redirecthtaccess 使用正则表达式和无限重定向重写规则
【发布时间】:2015-09-30 15:55:14
【问题描述】:

我很难使用 WP 的旧 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

新网址:

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

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

我的解决方案是在将https://stackoverflow.com/a/32852444/1090360https://stackoverflow.com/a/1279758/1090360 的答案结合起来后得出的

不知何故,用破折号替换下划线的部分会创建无限重定向并且服务器会冻结。如果我将通过将下划线替换为破折号来删除部分,那么其余部分都应该正常工作。

这是我的 .httaccess 规则

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

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

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

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

【问题讨论】:

    标签: .htaccess mod-rewrite url-rewriting rewrite url-redirection


    【解决方案1】:

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

    RewriteBase /
    
    # replace underscores with dashes 
    RewriteRule ^(news/index.php/.+?)_(.*) $1-$2 [L]
    
    # strip "news/index.php"
    RewriteRule ^news/index.php/(.*) /$1 [R=302,L]
    

    我使用N|next 标志对您的原始方法进行了更多操作,并且我的服务器也崩溃了。查看error.log,似乎这个无限循环是由Apache通过添加一个“路径信息后缀”创建的,它用原始URL放大了URL。所以它不断地用破折号替换下划线。

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

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

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


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

    【讨论】:

    • 当 URI 中存在像2014/11/07/my-blog-post-from-old-site_ 这样的尾随下划线时,我怎样才能让它工作?如果是下划线则删除最后一个字符
    • 只需将最后的(.+) 替换为(.*)。这也将匹配一个空字符串。另请参阅修改后的答案。这会更有效率,因为它不会在每次替换时都进行重定向。
    • 有没有办法跳过用破折号替换图像(.jpg、.png)上的下划线?
    • 在重写 RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png)$ [NC] 之前添加了该规则并且它有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多