.htaccess重写路径:新查询字符串首先删除首先跟踪斜杠的路径

时间:2014-11-06 20:03:54

标签: apache .htaccess mod-rewrite url-rewriting query-string

我有这段代码重写路径,然后重定向到子域名的文件夹:

RewriteEngine On
RewriteBase /

RewriteRule ^category/?$ category.php
RewriteRule ^category/[a-z0-9\-]+\_([A-Z0-9\_]+)/?$ articles.php?id=$1&section=category

RewriteCond %{HTTP_HOST} ^test.(.*)example.com/?$ [NC]
RewriteCond %{REQUEST_URI} !^/\!test/ [NC]
RewriteRule (.*) /!test/$1 [L,NC]

RewriteCond %{HTTP_HOST} ^example\.com$ [NC] 
RewriteRule ^(.*)$ http://www.example.com/$1 [NE,L,R=301]

最大的问题是在浏览器地址字段中键入此内容并按Enter:

http://test.example.com/category/article-about-something_35436

结束于它自身改变为:

http://test.example.comcategory/article-about-something_35436

浏览器当然告诉你“找不到服务器”。

疑难解答

我发现这很好用:

http://test.example.com/category

从第二次重写规则中删除查询字符串?id=$1&section=category。你当然不会在文章上结束,而是在articles.php上。

那么,有人知道这个问题吗?

1 个答案:

答案 0 :(得分:0)

重新排列规则并在其他内部重写规则之前使用R标记保留重定向规则:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^example\.com$ [NC] 
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

RewriteRule ^category/?$ category.php [L,NC]

RewriteRule ^category/[a-z0-9-]+_([A-Z0-9_]+)/?$ articles.php?id=$1&section=category [L,QSA]

RewriteCond %{HTTP_HOST} ^test\.(.*)example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/\!test/ [NC]
RewriteRule (.*) /!test/$1 [L,NC]