.htaccess:重定向尾部斜杠

时间:2016-06-27 08:03:27

标签: apache .htaccess redirect mod-rewrite trailing-slash

我在根目录的.htaccess文件中有一个重写规则:

RewriteEngine On

# Exclude .css / .js / ...
RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|png|js|css|swf|php|ico|txt|pdf|xml)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# Rewrite Rule
RewriteRule ^([^/]*)/([^/]*)$ /index.php?category=$1&product=$2

因此,网址http://example.com/data1/data2会向我category=data1product=data2

问题是以下网址无效:

http://example.com/data1          # Not Working (Page Not Found)
http://example.com/data1/data2/   # Not Working (Page Not Found)

但这些网址正在运作:

http://example.com/data1/         # Works -> category=data1
http://example.com/data1/data2    # Works -> category=data1 & product=data2

如何将前两个网址重定向到第二个网址?

OR / AND

执行所有URL重定向到非尾部斜杠的操作。所以下面的网址是:

http://example.com/data1/
http://example.com/data1/data2/

重定向到这些:

http://example.com/data1
http://example.com/data1/data2

1 个答案:

答案 0 :(得分:2)

要避免全部使用斜杠,请执行重定向

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R,L]

要将网址与一个元素匹配,您可以使用第二个规则

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php?category=$1&product= [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php?category=$1 [L]

全部放在一起

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R,L]

RewriteRule ^(.+?)/(.+)$ /index.php?category=$1&product=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php?category=$1 [L]