【问题标题】:Remove double 301 redirect from my htaccess?从我的 htaccess 中删除双 301 重定向?
【发布时间】:2016-07-19 15:00:11
【问题描述】:

我刚刚意识到我的 htaccess 在某些情况下会产生双 301 重定向。例如,如果您尝试访问http://example.com/old_url,它将:

这是我的 htaccess 的设置方式:

RewriteEngine On 

# Add www
RewriteCond %{HTTP_HOST} ^example.com [nocase]
RewriteRule ^(.*) http://www.example.com/$1 [last,redirect=301]

# Do some url rewriting
RewriteRule ^new_url_1$ new_url_1.php [NC,L]
RewriteRule ^new_url_2$ new_url_2.php [NC,L]

# Do the 301 redirections
Redirect 301 /old_url_1 http://www.example.com/new_url_1
Redirect 301 /old_url_2 http://www.example.com/new_url_2

我怎样才能解决这个问题,只有一个 301 以获得更好的 SEO?

【问题讨论】:

    标签: apache .htaccess url redirect http-status-code-301


    【解决方案1】:

    不要将Redirect 指令与mod_rewrite 规则混用,并在www 规则之前保留特定的重定向规则:

    RewriteEngine On 
    
    ## Unless directory, remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)/$ /$1 [NE,R=302,L]
    
    # Do specific 301 redirections
    RewriteRule ^old_url_1$ http://www.example.com/new_url_1 [L,NC,R=301]
    RewriteRule ^old_url_2$ http://www.example.com/new_url_2 [L,NC,R=301]
    
    # Add www
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]
    
    # Do some url rewriting
    RewriteRule ^new_url_1$ new_url_1.php [NC,L]
    
    RewriteRule ^new_url_2$ new_url_2.php [NC,L]
    

    确保在测试前清除浏览器缓存。

    【讨论】:

    • 谢谢,我会试试的。 Redirect 301 /old_url_1 http://www.example.com/new_url_1RewriteRule ^old_url_1/?$ http://www.example.com/new_url_1 [L,NC,R=301] 有什么区别?
    • RewriteRule 是 mod_rewrite 指令,Redirect 来自 mod_alias。不同的模块在不同的时间执行,将它们混合在一起可能会导致问题。
    • 那两者的具体区别呢?您添加了“/?”在网址中,还有“L,NC”作为选项。这有什么改变吗?
    • No /?$ 只允许一个可选的斜杠。 NC 用于忽略大小写匹配,L 用于结束规则。
    • 最后一个问题,如果我想从新的 url 中删除潜在的尾部斜杠,我应该在“添加 www”规则之前添加这个规则吗? RewriteRule ^new_url/$ http://www.example.com/new_url [L,NC,R=301]
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2016-10-07
    • 2023-03-18
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    相关资源
    最近更新 更多