首页 文章

.htaccess重写规则,友好的URL重定向

提问于
浏览
0

我正在使用.htaccess来获取看起来像这样的网址:

/index.php?page=2

并重写它们,例如:

/contact-us

我想做两件事:

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

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

哪个确实有效 . 但是现在我也希望导航到/index.php?page=2的人最终/联系我们 - 如何将这一点作为301重定向与友好的URL重写相结合?

2 回答

  • 0

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

    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标头 .

  • 0

    您可以在 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]
    

相关问题