删除URL中的尾随斜杠,但在Htaccess的某些特定情况下保留它
-
02-01-2020 - |
题
我知道如何在网址后删除斜杠,我知道如何添加它:
# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/$ /$1 [L,R=301]
# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*[^/]$ /$0/ [L,R=301]
.
我想要的是删除所有斜杠,以便所有URL都没有在结束时斜线,但在一个情况下,URL应该包含斜杠。
1.)只有在这种情况下,它应该添加斜杠:
example.com/en - > example.com/en /
2.)在任何其他情况下,应删除斜杠:
example.com/us/ - > example.com/us
example.com/en/product/ - > example.com/en/product
如何用.htaccess规则进行操作?
解决方案
这是一个奇怪的问题。
无论如何,您可以将此代码放在您的htaccess(它应该是root
文件夹中)
RewriteEngine on
# add trailing slash when url is /en
RewriteRule ^en$ /en/ [R=301,L]
# otherwise, remove trailing slash (except for /en/ and existing folders)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/en/$ [NC]
RewriteRule ^(.+)/$ /$1 [R=301,L]
. 不隶属于 StackOverflow