【问题标题】:.htaccess redirect 301 using rewrite rule.htaccess 使用重写规则重定向 301
【发布时间】:2011-05-26 21:24:45
【问题描述】:

我正在尝试美化一些网址。我配置了 htaccess 文件,所以我的 url 被改变了:

旧网址:http://mysite.com/index.php?id=45tye4 新网址:http://mysite.com/45tye4

我现在想将旧网址永久重定向到新网址。这是我没有运气的尝试:

RewriteRule ^index.php?id=(.*)$ $1 [R=301,L]

主要问题似乎是“?”在网址中。当我尝试相同的 url 时没有 ?重定向有效。我还尝试了其他变体但没有运气:

RewriteRule ^index.php\?id=(.*)$ $1 [R=301,L]
RewriteRule ^index.php[\?]id=(.*)$ $1 [R=301,L]

更新:

我根据 anubhava 指令添加了重定向。重定向有效,但不幸的是我进入了重定向循环。我认为 [L] 标志应该解决重定向循环,但它没有。

RewriteCond %{QUERY_STRING} ^id=(.*)$
RewriteRule ^index\.php/?$ /%1? [R=301,L] 

RewriteRule ^(.*)$ index.php?id=$1 [L]

【问题讨论】:

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


    【解决方案1】:

    RewriteRule 仅匹配 REQUEST_URI。您必须使用 RewriteCond 来匹配查询字符串

    试试这个代码:

    Options +FollowSymlinks -MultiViews
    RewriteEngine on
    
    RewriteCond %{THE_REQUEST} ^GET\s/+index\.php [NC]
    RewriteCond %{QUERY_STRING} (^|&|\?)id=(.*)(&|$) [NC]
    RewriteRule . /%2? [R=301,L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)$ index.php?id=$1 [L]
    

    这会将 /index.php?id=45tye4 的旧 URI 重定向到新 URI:/45tye4

    【讨论】:

    • 重定向有效,但不幸的是我进入了重定向循环。我认为 [L] 标志应该解决重定向循环,但它没有。
    • 有一个小错字,编辑了答案。请再次检查。
    • 我添加了更新的,但我仍然遇到重定向循环问题。我不明白,[L] 标志不应该避免它吗?
    • 我之前没有注意到您在 EDIT 部分中的代码。基于此,我不得不改变我的答案。我已经对它们进行了测试,并且工作正常。请检查。
    • 我已经相应地更新了它,仍然无法正常工作。重定向循环已损坏,但 301 重定向不起作用。出于某种奇怪的原因,mysite.com/index.php?id=465 类型的 url 的 THE_REQUEST 条件不正确。
    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 2010-12-22
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多