htaccess - 重写规则 - 在重写url后重定向

时间:2018-04-25 01:30:06

标签: .htaccess url-rewriting

这很简单,但似乎无法解决这个问题。

我有一个网址 /shows/index.php?id=1 ,我希望将其作为 /shows/1/index.php 显示在网址中。< / p>

所以我把它添加到我的htaccess:

RewriteRule ^shows/([0-9]*)/index.php$ /shows/index.php?id=$1 [L]

这就像一个魅力。我现在可以导航到 /shows/1/index.php 根本没问题。但是,我仍然可以导航到 /shows/index.php?id=1 。我希望该页面自动重定向到新的URL,所以我写了这个:

RewriteRule ^shows/index.php?id=([0-9]*)$ /shows/$1/index.php [R=301,L]

......但它没有做任何事情。但是,如果我做了类似的事情:

RewriteRule ^shows/([0-9]*)/0$ /shows/$1/index.php [R=301,L]

重定向很好。这让我觉得重写规则的第一部分存在问题,也许?我对这类东西不太熟悉。

1 个答案:

答案 0 :(得分:1)

由于您要重定向并重写相同的请求,因此需要与%{THE_REQUEST}变量匹配,否则您将在重定向上遇到无限循环错误

 RewriteEngine on

# redirect /shows/index.php?id=1 to /shows/1/index.php
RewriteCond %{THE_REQUEST} /shows/index.php\?id=([^\s]+) [NC]
RewriteRule ^shows/index.php$ /shows/%1/index.php? [NC,L,R]
#rewrite /shows/1/index.php to /shows/index.php?id=1
RewriteRule ^shows/([0-9]*)/index.php$ /shows/index.php?id=$1 [L]

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