【问题标题】:.htaccess Rewrite Rules, friendly URLs + redirect.htaccess 重写规则,友好的 URLs + 重定向
【发布时间】:2015-06-03 20:21:07
【问题描述】:

我正在使用 .htaccess 获取如下所示的 URL:

/index.php?page=2

并将它们重写为,例如:

/contact-us

我想做两件事:

加载 /contact-us 时,显示页面 /index.php?page=2 但保留友好的 URL。我知道这看起来像:

RewriteRule ^contact-us$ "index\.php\?page\=2" [L]

哪个工作正常。但现在我还希望导航到 /index.php?page=2 的人最终访问 /contact-us - 我如何通过 301 重定向和友好的 URL 重写来实现这一点?

【问题讨论】:

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


    【解决方案1】:

    不确定为什么要在重写规则的目标部分使用引号和转义符。目标部分不是正则表达式。这可以简单地看起来像:

    RewriteRule ^contact-us$ /index.php?page=2 [L]
    

    要重定向 index.php?page=2,您需要执行以下操作。此规则必须在上述规则之前,否则您将进入重写循环。

    RewriteCond %{REQUEST_URI}  ^/index\.php$
    RewriteCond %{QUERY_STRING} ^page=2$
    RewriteRule .* /contact-us [R=301,L]
    

    这里你设置了两个重写条件:页面是/index.php,查询字符串是page=2(并且只有page=2)。 R=301 标志将强制对 /contact-us 进行外部重写,并发送 HTTP 301 标头。

    【讨论】:

    • RewriteRule ^index\.php?page=12$ /addiction-treatment-recovery-programs [R=301,L] RewriteRule ^addiction-treatment-recovery-programs$ index.php?page=12 [L] 这看起来正确吗?
    • @SarahBee 查看我的最新更新。我最初没有正确显示重写规则。
    • RewriteCond %{REQUEST_URI} ^/index\.php$ RewriteCond %{QUERY_STRING} ^page=12$ RewriteRule .* /addiction-treatment-recovery-programs [R=301,L] RewriteCond %{HTTP_HOST} ^edgewood.ca$ [OR] RewriteCond %{HTTP_HOST} ^www\.edgewood.ca$ RewriteRule ^addiction-treatment-recovery-programs$ index.php?page=12 [L] 抱歉,我的迷你降价格式有点失败。我现在有了这个和一个重定向循环。它还使用查询字符串重定向 (/addiction-treatment-recovery-programs?page=12)
    • 好的,我知道我必须添加问号来阻止查询字符串,但仍然不确定如何避免这个重定向循环。
    • @SarahBee 您应该使用最新代码更新您的 OP。很难说你在做什么。从您所展示的内容中我看不到会导致重定向循环的原因。我不知道为什么你有第二个重写规则的重写条件。
    【解决方案2】:

    您可以在 DOCUMENT_ROOT/.htaccess 文件中使用此代码:

    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{THE_REQUEST} /index\.php\?page=2[&\s] [NC]
    RewriteRule ^ contact-us? [R=302,L,NE]
    
    RewriteRule ^contact-us/?$ index.php?page=2 [L,QSA,NC]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多