.htaccess redirect / abc / def / to / abc / def但不是以/ xxx / yyy /开头的URL?

时间:2018-01-30 14:12:20

标签: apache .htaccess mod-rewrite

我在.htaccess中将/abc/def/重定向到/abc/def,删除尾部斜杠:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

效果很好。现在,我想要排除以/xxx/yyy/开头的网址,以免被上述规则重定向,例如: /xxx/yyy/12345/需要保留,因为没有被重定向到/xxx/yyy/12345,保留尾随斜杠。

所以我有:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/xxx/yyy/
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

但由于/xxx/yyy/12345/仍被重定向到/xxx/yyy/12345,因此无效。我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

使用THE_REQUEST变量代替REQUEST_URI因为REQUEST_URI因执行其他规则而可能会发生变化:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} !\s/+xxx/yyy/ [NC]
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^ %1 [L,R=301,NE]

确保使用新的浏览器进行测试。

答案 1 :(得分:0)

这似乎是因为我在.htaccess中有这个:

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^ index.php [L]
RewriteRule ^(.*)$ public/$1 [L]

在上一个目录中。所以我必须使用的是:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/public/xxx/yyy/
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

/public/之前添加/xxx/yyy/,但公开网址实际上是/xxx/yyy/

相关问题