2

您好在我的项目中,我有以下 htaccess。一切正常,例如我输入以下网址domain.com/ test some test / test /

domain.com/test+some+test/test 正如预期的那样

至少对我来说奇怪的是当我编辑domain.com/test+some+test/test

domain.com/test+some+test         /test

然后再次按回车键,结果如下:

domain.com/test+some+test%20%20%20%20%20/test

不应该再次逃脱吗?如果我遗漏了什么,请指出。

Options All -Indexes +FollowSymLinks -MultiViews

    <IfModule mod_rewrite.c>

        # Turn mod_rewrite on
        RewriteEngine On
        RewriteBase /

        # remove spaces from start or after /
        RewriteRule ^(.*/|)[\s%20]+(.+)$ $1$2 [L]
        # remove spaces from end or before /
        RewriteRule ^(.+?)[\s%20]+(/.*|)$ $1$2 [L]


        # replace spaces by + in between
        RewriteRule ^([^\s%20]*)(?:\s|%20)+(.*)$ $1+$2 [L,R=301]


        # Remove trailing slash
        RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [L,R=301]

        # Add trailing slash
        #RewriteCond %{REQUEST_URI} !(/$|\.) 
        #RewriteRule (.*) %{REQUEST_URI}/ [L,R=301] 

        # Remove multiple slashes
        RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/{2,} [NC]
        RewriteRule ^(.*) $1 [R=301,L]

        # Clean url rewrite
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} !^.*\.(png|jpg|jpeg|bmp|gif|css|js|json)$ [NC]
        RewriteRule ^(.*)$ /index.php?req=$1 [L,QSA]

    </IfModule>

更新

经过进一步调查并按照 Anubhava 的建议在前 2 个重写器上应用 R 开关后,仅剩 1 个问题

如果我输入 http://tms.localhost/test+some+test /test它会变成http://tms.localhost/test+some+test%20%20%20/test但是如果我这样输入它http://tms.localhost/test some test /test就会变成预期的那样http://tms.localhost/test+some+test/test

4

2 回答 2

1

在应用任何重写规则之前编码+解码的空间。这意味着这个正则表达式模式:匹配空格、百分号、2 和 0。%20[\s%20]

该正则表达式只需:

    # remove spaces from start or after /
    RewriteRule ^(.*/|)[\s]+(.+)$ $1$2 [L]
    # remove spaces from end or before /
    RewriteRule ^(.+?)[\s]+(/.*|)$ $1$2 [L]

问题是,如果浏览器请求:/test+test%20test//test%20test+test/,这将被翻译为(space) 无论如何。因此,您需要匹配实际请求:

# replace spaces by + in between
RewriteCond %{THE_REQUEST} \ /(.*?)(%20)+([^\?\ ]*)
RewriteRule ^ /%1+%3 [L,R=301,NE]
于 2013-09-27T19:27:50.087 回答
0

在最初的 2 条规则中添加R标志:

# remove spaces from start or after /
RewriteRule ^(.*/|)[\s%20]+(.+)$ $1$2 [L,R,NE]
# remove spaces from end or before /
RewriteRule ^(.+?)[\s%20]+(/.*|)$ $1$2 [L,R,NE]
于 2013-09-27T19:30:37.843 回答