Wednesday, June 6, 2018

Remove multiple trailing slashes in root using htaccess

Leave a Comment

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] 

4 Answers

Answers 1

Try with:

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

Answers 2

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.

Answers 3

You just need two rule to match two different pattern

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

Answers 4

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment