.htaccess多次重写规则/优先级

时间:2014-06-18 18:05:19

标签: php .htaccess mod-rewrite url-rewriting

这是我当前的htaccess文件:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.website\.com [NC]
RewriteCond %{HTTP_HOST} ([^.]+)\.website\.com [NC]
RewriteRule ^(.*)$ http://www.website.com/gotourl.php?urlid=?%1 [L]
RewriteRule    ^(\w+)$ ./gotourl.php?urlid=$1    [NC,L]    
RewriteRule    ^(\w+)/$ ./gotourl.php?urlid=$1    [NC,L]   

有问题的网站是我正在进行测试/开发和个人使用的URL缩短程序。上面的代码可能并不理想,因为我不熟悉.htaccess并通过谷歌搜索和测试来实现。这就是我想要的URL缩短方面:

http://website.com/1234 -> http://website.com/gotourl.php?urlid=1234
http://website.com/1234/ -> http://website.com/gotourl.php?urlid=1234

问题是我无法弄清楚如何让它忽略某些目录。我希望特定目录转到特定页面:

http://website.com/img (or) http://website.com/img/ -> http://website.com/img.php
http://website.com/img/1234 (or) http://website.com/img/1234/ -> http://website.com/viewimage.php?imgid=1234

主要问题是我不知道如何正确地做到这一点,我尝试这样做的方式总是会改写为:

http://website.com/gotourl.php?urlid=XXXX

或最终无限循环的重定向,而不是去我想要的特定页面。任何帮助表示赞赏。

本质上,我正在寻找帮助编写我的htaccess来执行以下操作:

URL user visits -> URL user sees
http://website.com/img -> http://website.com/img.php
http://website.com/img/XXXX -> http://website.com/viewimage.php?imgid=XXXX
http://website.com/XXXX -> http://website.com/gotourl.php?urlid=XXXX

所有路径都应该使用或不使用尾部斜杠。

寻求帮助,让它可以做到这一点,可能会对每条线的实际含义进行一些解释,以便我可以从中学习。

1 个答案:

答案 0 :(得分:0)

您想要改变的主要方面是让您的规则更具体。您缩短的网址可能不包含斜线或点,因此您可以将网址缩短网址更改为:RewriteRule ^([^/\.]+)/?$ gotourl.php?urlid=$1 [NC,L]。你需要预防' gotourl.php'从匹配那个。仅img的规则更具体,应该首先完成。 img / something的规则稍微不那么具体,可以在任何地方。

RewriteEngine On

RewriteRule ^img/?$ img.php [L]
RewriteRule ^img/([^/]+)/?$ viewimage.php?imgid=$1 [L]
RewriteCond %{HTTP_HOST} !^www\.website\.com [NC]
RewriteCond %{HTTP_HOST} ([^.]+)\.website\.com [NC]
RewriteRule ^(.*)$ http://www.website.com/gotourl.php?urlid=%1 [L]
RewriteRule ^([^/\.]+)/?$ gotourl.php?urlid=$1 [NC,L]
相关问题