【问题标题】:Using a .htaccess to RewriteRule and Redirect 301 at the same time?同时使用 .htaccess 来 RewriteRule 和 Redirect 301?
【发布时间】:2014-07-27 14:02:21
【问题描述】:

我有几个特定的​​ URL,我想在我的网站上以不同的方式显示。例如,我希望“/contact.php”变成“/contact”。所以我将此添加到我的 .htaccess 中:

RewriteRule ^contact$ contact.php

为了避免两个不同的 URL 指向同一个页面,我还想在旧 URL 和新 URL 之间进行 301 重定向:

Redirect 301 /contact.php http://www.example.com/contact  

上面的每一行都可以单独运行。但是如果我将它们都添加到我的 htaccess 中,我就会有一个重定向循环。我该如何解决?

最后,如果我输入“/contact”或“/contact.php”,我希望看到带有 url “/contact”的联系人页面。


编辑:我也尝试过类似的方法,但它不起作用:

RewriteRule ^/contact\.php$ http://www.example.com/contact [R=301,L]
RewriteRule ^/contact$ /contact.php [L]

【问题讨论】:

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


    【解决方案1】:

    是的,它确实会导致重定向循环,因为mod_rewrite 规则是在循环中应用的。 这里REQUEST_URI 的值在第一条规则之后更改为contact.php,在第二条规则之后更改为contact规则。

    为避免这种循环,您需要在外部重定向规则中使用%{THE_REQUEST},因为THE_REQUEST 变量代表Apache 从您的浏览器收到的原始请求,并且在执行其他一些重写规则后它不会被覆盖。此变量的示例值为GET /index.php?id=123 HTTP/1.1

    使用这个:

    RewriteEngine On
    
    # external redirect from /contact.php to /contact  
    RewriteCond %{THE_REQUEST} \s/+(contact)\.php\[\s?] [NC]
    RewriteRule ^ /%1? [R=302,L]
    
    # internal forward from /contact to /contact.php
    RewriteRule ^(contact)/?$ $1.php [L,NC]
    

    一旦您确定它适合您,请将 302 更改为 301

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 2012-02-24
      • 2013-03-14
      • 2010-09-10
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多