I am using the following htaccess rul to remove double or more slashes from web urls:
#remove double/more slashes in url
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]
This is working fine for slashes occured in the middle of uris, such as, If use url:
http://demo.codesamplez.com/html5//audio
Its being redirected to proper single slahs url:
http://demo.codesamplez.com/html5/audio
But if the url contains double slashes in the beginning, JUST AFTER the domain name, then there its not working, example:
http://demo.codesamplez.com//html5/audio
its not being redirected.
How I can fix the above rule to work for this type of urls as well? Thanks.
For me, the following rules work perfectly:
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 likeGET /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.Give it a try with:
It should redirect to a single slash at the end of the domain. And an improvement on yours:
As per this link, following code should take care of extra slashes(anywhere) in URL.
To prevent long repetition of characters in your url such as:
you can do:
It should works with :
see also: .htaccess - how to remove repeated characters from url?