【问题标题】:Apache mod_rewrite friendly URLs with corresponding 301 redirects具有相应 301 重定向的 Apache mod_rewrite 友好 URL
【发布时间】:2012-03-11 17:06:08
【问题描述】:

问题:

我一直在旋转我的轮子并阅读了一段时间,现在寻求一些帮助。我正在寻找一组不友好的 URL(实际上有更多的“组”,但这应该以我为例):

  1. domainname.com/?section=zebras
  2. domainname.com/?section=monkeys&id=555

并将它们转换为友好的 URL,以及在旧版本上执行 301,以便任何旧书签(和搜索引擎)仍然可以解析它们。我正在寻找的新格式是:

  1. domainname.com/zebras/
  2. domainname.com/monkeys/555

我完全打算为每个场景编写单独的 RewriteCond/RewriteRule 组合,所以我不一定需要一个超级规则来捕获我的所有场景。哦,这一切都在 .htaccess 中。

我的进步:

我最初进入重定向循环是因为我只是背靠背地执行两个 RewriteRules - 一个用于友好 URL,一个用于 301 重定向。在重定向循环周围遇到了我最喜欢的方式(到目前为止)(至少对于我的场景#1):

RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteCond %{QUERY_STRING} ^section=zebras$ [NC]
RewriteRule ^.*$ http://www.domainname.com/zebras/? [R=301,NC,L]

RewriteRule ^zebras/$ /index\.php?section=zebras [NC,L]

但是,我希望有一些不仅仅适用于“斑马”的东西(例如,我希望它也适用于“狮子”),所以我试图让它更通用.我现在正在尝试的看起来像这样:

RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteCond %{QUERY_STRING} ^section=([a-z]+)$ [NC]
RewriteRule ^section=([a-z]+)$ http://www.domainname.com/$1/? [R=301,NC,L]

RewriteRule ^([a-z]+)/$ /index\.php?section=$1 [NC,L]

但是,这不起作用。我想我有一些“不太正确”的东西,我只是不知道它是什么——我在某处遗漏了一些东西或格式不正确。提前很抱歉描述冗长,只是想清楚一点。

【问题讨论】:

    标签: mod-rewrite url-rewriting http-status-code-301 seo


    【解决方案1】:

    这样做:

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule ^ - [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_URI} !(\.\w+|/)$ 
    RewriteRule (.*) /$1/ [R,L]
    
    RewriteCond %{QUERY_STRING} ^section=([a-z]+)$ [NC]
    RewriteRule ^ /%1/? [R=301,NC,L]
    
    RewriteRule ^([a-z]+)/$ /index\.php?section=$1 [NC,L]
    
    RewriteCond %{QUERY_STRING} ^section=([a-z]+)&id=(\d+)$ [NC]
    RewriteRule ^ /%1/%2/? [R=302,NC,L]
    
    RewriteRule ^([a-z]+)/(\d+)/$ /index\.php?section=$1&id=$2 [NC,L]
    

    说明

    防止循环:

    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule ^ - [L]
    

    防止斜杠问题:

    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_URI} !(\.\w+|/)$ 
    RewriteRule (.*) /$1/ [R,L]
    

    处理仅包含 section=([a-z]+) 的重写:

    RewriteCond %{QUERY_STRING} ^section=([a-z]+)$ [NC]
    RewriteRule ^ /%1/? [R=302,NC,L]
    
    RewriteRule ^([a-z]+)/$ /index\.php?section=$1 [NC,L]
    

    处理仅包含 section=([a-z]+)&id=(\d+) 的重写:

    RewriteCond %{QUERY_STRING} ^section=([a-z]+)&id=(\d+)$ [NC]
    RewriteRule ^ /%1/%2/? [R=302,NC,L]
    
    RewriteRule ^([a-z]+)/(\d+)/$ /index\.php?section=$1&id=$2 [NC,L]
    

    你的规则有误:

    section=([a-z]+) 在 URI 部分中不可用。所以,RewriteRule ^section=([a-z]+)$ 永远不会匹配。

    【讨论】:

    • 这太棒了,今晚晚些时候试一试,看看效果如何。您使用 302 重定向而不是 301 的任何原因?我认为我可以安全地用 301 替换那些,因为我将处理永久重定向而不是临时重定向?还要感谢您指出我原始代码中的缺陷 - 现在我认为它是正确的。
    • @vladimir 使301。这是一个错字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2013-05-26
    • 1970-01-01
    • 2014-02-24
    相关资源
    最近更新 更多