Issue In Removing Double Or More Slashes From URL By .htaccess

跟風遠走 提交于 2019-11-28 23:38:39

Give it a try with:

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

It should redirect to a single slash at the end of the domain. And an improvement on yours:

RewriteCond %{REQUEST_URI} ^(.*)/{2,}(.*)$
RewriteRule . %1/%2 [R=301,L]

For me, the following rules work perfectly:

<IfModule mod_rewrite.c>
    RewriteBase /

    # rule 1: remove multiple leading slashes (directly after the TLD)
    RewriteCond %{THE_REQUEST} \s/{2,}
    RewriteRule (.*) $1 [R=301,L]

    # rule 2: remove multiple slashes in the requested path
    RewriteCond %{REQUEST_URI} ^(.*)/{2,}(.*)$
    RewriteRule (.*) %1/%2 [R=301,L]
</IfModule>

The idea is heavily based on Marcels answer (thanks!), but this one is a bit more lightweight and includes the RewriteBase, which may be helpful if you work with specific subdirectory structures. Additionally, Marcels answer lacks explanation, which I wanted to fix:

Rule 1: {THE_REQUEST} contains something like GET /index.html HTTP/1.1 (see docs). Hence, if we match the first whitespace (\s) followed by multiple slashes (/{2,}), we can access the correct URL without the leading double slash via $1.

Rule 2: The regular expression ^(.*)/{2,}(.*)$ splits the request URI on multiple slashes. %1/%2 then combines the two splitted strings again, but with only one slash at this time.

RafaSashi

To prevent long repetition of characters in your url such as:

http://demo.codesamplez.com/html5///////////////////////////////////////////audio

you can do:

RewriteCond %{REQUEST_METHOD}  !=POST
RewriteCond %{REQUEST_URI} ^(.*?)(/{2,})(.*)$
RewriteRule . %1/%3 [R=301,L]

It should works with :

http://demo.codesamplez.com//html5/audio

see also: .htaccess - how to remove repeated characters from url?

As per this link, following code should take care of extra slashes(anywhere) in URL.

RewriteCond %{THE_REQUEST} //
RewriteRule ^.*$ $0 [R=302,L,NE]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!