如何在1个RewriteRule中删除/ 301 Trailing Slash,并在其余站点添加Trailing Slash?

时间:2013-09-11 15:11:34

标签: regex apache .htaccess mod-rewrite

目前我有一个htaccess重写,允许尾部斜杠或没有尾部斜杠。

RewriteRule ^trams/([a-zA-Z\-]+)/([a-zA-Z0-9\-]+)/([0-9-]+)/?$ trams/more_details.php?id=$3&tram=$1 [QSA,NC,L]

对于上面这个特定的重写,我正在尝试更改它,以便如果该URL有一个尾部斜杠,它301重定向到版本而不用一个尾部斜杠,但是我不确定要添加到上面的那行?

更复杂的是,htaccess文件顶部有一段代码,它会在整个网站的某些网址上添加一个斜杠(这是网站其他部分的要求,对不一致感到遗憾),等等我还需要找出我需要添加到下面的块中的哪一行,以便忽略上述规则....

# If requested resource does not exist as a file
RewriteCond %{REQUEST_FILENAME} !-f
# and does not end with a period followed by a filetype
RewriteCond %{REQUEST_URI} !\..+$
# and does not end with a slash
RewriteCond %{REQUEST_URI} !/$
# then add a trailing slash and redirect
RewriteRule (.*) http://%{HTTP_HOST}/$1/ [R=301,L]

1 个答案:

答案 0 :(得分:1)

要从给定的网址格式中删除尾部斜杠:

RewriteRule ^(trams/[\w-]+/[\w-]+/[\d-]+)/$ $1 [R=301,L]

# If requested resource does not exist as a file 
RewriteCond %{REQUEST_FILENAME} !-f 
# and does not end with a period followed by a filetype 
RewriteCond %{REQUEST_URI} !\..+$ 
# URL is not the one we don't want a trailing slash
RewriteCond %{REQUEST_URI} !^/trams/[\w-]+/[\w-]+/[\d-]+$ 
# then add a trailing slash and redirect 
RewriteRule ^(.+?[^/])$ http://%{HTTP_HOST}/$1/ [R=301,L]

PS:请务必将此规则置于所有其他现有规则之上。