【问题标题】:Correct RegEx to avoid infinte loop using RewriteRule to redirect 301更正正则表达式以避免使用重写规则重定向 301 的无限循环
【发布时间】:2013-08-09 16:25:59
【问题描述】:

我试图告诉我的服务器重定向以下请求:

http://example.es
http://example.es/
http://example.es/es
http://example.es/es/
http://www.example.es
http://www.example.es/
http://www.example.es/es

到这个页面:

http://www.example.es/es/

为了做到这一点,我的 .htaccess 中有以下内容

#RewriteEngine On    # Turn on the rewriting engine
RewriteBase /
RewriteCond %{HTTP_HOST} ^(\.?example\.es(/|/es|/es/)?|www\.?example\.es(/|/es)?)$ [NC]
RewriteRule ^(.*)$ http://www.example.es/es/ [R=301,L]

问题在于它会导致无限重定向,因为想要的 URL http://www.example.com/es/ 也包含 HTTP_HOST 字符串。问题是我找不到准确的正则表达式来避免这个问题。

.htaccess 的其余部分如下:

php_flag register_long_arrays on
php_flag register_globals on
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css javascript application/javascript
ExpiresActive On
ExpiresByType text/css "access plus 1 years"
ExpiresByType image/png "access plus 1 years"
ExpiresByType application/javascript "access plus 1 years"

Header set Connection keep-alive

非常感谢您的帮助!

干杯!

【问题讨论】:

    标签: regex .htaccess mod-rewrite apache2 http-status-code-301


    【解决方案1】:

    AFAIK Apache 的重写使用 PERL 正则表达式,因此支持负前瞻。您可以使用一个来避免将http://www.example.com/es/ 与自身匹配。试试:

    ^(\.?example\.com(/|/es|/es/)?|www\.?example\.com(/|/es(?!/))?)$

    【讨论】:

      【解决方案2】:

      请记住,%{HTTP_HOST} 仅匹配 URL 中的主机名。

      用这个替换你的代码:

      Options +FollowSymLinks -MultiViews
      # Turn mod_rewrite on
      RewriteEngine On
      
      RewriteCond %{HTTP_HOST} ^(www\.)?(example\.ws)$ [NC]
      RewriteRule (?!^es/)^(.*)$ http://www.%1/es/$1 [R=301,L,NC]
      

      【讨论】:

      • 对不起!为了有一个更好的例子,我使用了 .com 域,但我的案例确实附加到 .es。我改变了原来的问题。对于错误的示例,所有请求都可以正常工作,除了 www.example.com/es 重定向到 404 页面并显示以下消息“在此服务器上找不到请求的 URL /es/es。”。我想是因为我的例子不正确。此外,我了解 RewriteCond 正则表达式,但对 RewriteRule 真的一无所知。为什么是两个^? ^ 是字符串的开头,对吧?
      • 这实际上是一个负前瞻,这意味着对所有 URL 执行 RewriteRule,除非 URL 开始 /es/
      • 我做了一个小修改以适应您的最新示例。立即尝试。
      • 仍有问题 1) example.es/ 重定向到 www./es/ 2) example.es/es 重定向到 /es/es 3) www.example.es/ 重定向到 www.www ./es/ 4) www.example.es/es 重定向到 www.www./es/es 顺便说一下,R​​ewriteCond 是正确的,正则表达式以“ws”而不是“es”结尾?我认为是一个错字。
      • 有什么问题,请提供详细信息。还要在您的问题中复制/粘贴完整的 .htaccess。
      【解决方案3】:

      我得到这样的答案:

      Options +FollowSymLinks -MultiViews
      RewriteEngine On    # Turn on the rewriting engine
      RewriteCond %{HTTP_HOST} ^(www\.)?(example\.es)$ [NC]
      RewriteRule ^(/|/es|/es/)?$ http://www.example.es/es/$1 [R=301,L,NC]
      

      谢谢大家的帮助!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-10
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        • 2015-05-23
        • 2011-03-03
        • 2018-05-31
        • 2012-06-21
        相关资源
        最近更新 更多