我在根目录的.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=data1
和product=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
答案 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]