Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple trailing slashes in root using htaccess

Tags:

.htaccess

I have a rule in my htaccess file to remove any extra trailing slashes from a url, this works on sub-directories with any more than 1 trailing slash. However it doesn't work on the root; which i need it to do.

For example.

http://www.example.com/test//// Redirects to http://www.example.com/test/

http://www.example.com/// Needs to redirect to http://www.example.com

Any ideas on what i need to add?. Cheers.

RewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$
RewriteRule . %1/ [R=301,L]
like image 613
LazyAlpine Avatar asked Oct 25 '17 12:10

LazyAlpine


3 Answers

For removing multiple slashes anywhere in REQUEST_URI this rule works best:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s[^?]*//
RewriteRule ^.*$ /$0 [R=301,L,NE]

It takes advantage of the fact that mod_rewrite engine itself converts all multiple forward slashes to a single slash in the RewriteRule pattern. We use RewriteCond %{THE_REQUEST} to make sure original REQUEST_URI contains multiple slashes.

like image 172
anubhava Avatar answered Oct 25 '22 20:10

anubhava


Try with:

RewriteCond %{REQUEST_URI} ^(.*?)//+$
RewriteRule ^ %1/ [R=301,L]
like image 35
Croises Avatar answered Oct 25 '22 20:10

Croises


You htaccess works great as you can test on below link

https://htaccess.madewithlove.be/

Working

So you need to make sure you test either with a Chrome Incognito window or using like below

curl -v http://example.com////

I usually prefer curl as I know it will give a fresh response from the server always

like image 22
Tarun Lalwani Avatar answered Oct 25 '22 20:10

Tarun Lalwani