Htaccess添加并强制尾随斜杠

时间:2018-03-07 19:06:32

标签: .htaccess redirect url-redirection

我的htaccess代码遇到了一些问题:

RewriteEngine on

RewriteRule ^about\/$ /about.php [L]
RewriteRule ^about?$ /about/ [L,R]

RewriteRule ^contact\/$ /contact.php [L]
RewriteRule ^contact?$ /contact/ [L,R]

RewriteRule ^([A-Za-z0-9\-]+)\/gallery\/$ /loc-gallery.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)\/gallery?$ /$1/gallery/ [L,R]

RewriteRule ^([A-Za-z0-9\-]+)\/location\/$ /loc-location.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)\/location?$ /$1/location/ [L,R]

RewriteRule ^([A-Za-z0-9\-]+)\/contact\/$ /loc-contact.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)\/contact?$ /$1/contact/ [L,R]

RewriteRule ^([A-Za-z0-9\-]+)\/$ /loc-home.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)?$ /$1/ [L,R]

问题在于,如果我想访问:

http://example.com/about
http://example.com/contact

我没有被重定向到

`http://example.com/about/` and `http://example.com/contact/`

当我尝试访问http://example.com/时,我被重定向到http://example.com//

我做错了什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

当您尝试访问http://example.com/时,由于此行,我被重定向到http://example.com//

RewriteRule ^([A-Za-z0-9\-]+)?$ /$1/ [L,R]

由于此正则表达式^([A-Za-z0-9\-]+)?$,它将匹配空URI 它表示匹配([A-Za-z0-9\-]+)然后是?

它应该是这样的:

RewriteRule ^([A-Za-z0-9\-]+)$ /$1/ [L,R]

我还对你的代码进行了羞辱并解决了一些类似的问题:

RewriteEngine on
RewriteRule ^about(\/)?$ /about.php [L]
RewriteRule ^contact(\/)?$ /contact.php [L]
RewriteRule ^([A-Za-z0-9\-]+)\/gallery(\/)?$ /loc-gallery.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)\/location(\/)?$ /loc-location.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)\/contact(\/)?$ /loc-contact.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)\/$ /loc-home.php?slug=$1 [L]
RewriteRule ^([A-Za-z0-9\-]+)$ /$1/ [L,R]

清除浏览器缓存并对其进行测试,如果可以,请将R更改为R=301以获得永久重定向