Htaccess从最后一个斜杠后面的URL中删除字符串

时间:2015-10-25 04:58:24

标签: apache .htaccess url mod-rewrite

寻找解决方案如何删除最后一个斜杠后面的任何内容。

示例输出网址:

http://example.com/pictures/123/category-name/

此网址要避免的问题:

http://example.com/pictures/123/category-name/blah.html
http://example.com/pictures/123/category-name/blah/blah.html
http://example.com/pictures/123/category-name/blah/blah/blah.html
http://example.com/pictures/123/category-name/blah/
http://example.com/pictures/123/category-name/blah

到目前为止我有这个:

RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name/$ $1/$2/category-name/ [R]
RewriteRule ([A-Za-z0-9-]+)/([0-9]+)/category-name/(.*)$ category.php?VarA=$1&VarB=$2

它适用于输出URL和带有模式后面的任何内容的URL。问题是,如果在最后一个斜杠后面有任何内容,它不会重写(重定向)到输出URL。

1 个答案:

答案 0 :(得分:1)

我个人使用像这样直截了当的逻辑:

#redirect to canonical url if no ending slash
RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name$ $1/$2/category-name/ [R,L]
#redirect to canonical url if anything behind slash
RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name/(.+)$ $1/$2/category-name/ [R,L]
#rewrite to PHP file if visiting the canonical url
RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name/$ category.php?VarA=$1&VarB=$2 [L]