Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing multiple groups of slashes everywhere in URL in .htaccess

I currently have a website where guests are able to access each url with any number of slashes to separate folder names. For example, if a URL is supposed to be:

http://example.com/one/two/three/four

Then users could access the same page via any of the following:

http://example.com/one//two///three////four/////
http://example.com/one/two////three/four/////
http://example.com///one///////////two////three/four/
http://example.com///////////one///////////two/three/four

However, I want the above example urls to only redirect users to this URL:

http://example.com/one/two/three/four

This is my .htaccess file to attempt to stop the enormous slashes:

RewriteCond %{ENV:REDIRECT_STATUS} !^$
RewriteRule .* - [L]
RewriteRule ^(.*)/+$ /$1 [R=301,L,NC]
RewriteCond %{REQUEST_URI} ^/+(.*)/+$
RewriteRule .* /%1 [R=301,L]

The third line successfully stops trailing slashes on long URLs. The 4th and 5th lines are my attempt to stop trailing slashes right after the domain name, but that was unsuccessful.

The reason why I ask this question is because I don't want google to catch me for duplicate content and with adsense active on the site, google will likely scan all the URLs that I access.

Is there a RewriteCond/RewriteRule combo I can use to strip the middle slashes or is it more involved?

like image 760
Mike -- No longer here Avatar asked Sep 02 '25 09:09

Mike -- No longer here


1 Answers

You can use this rule for removing multiple slashes anywhere in URL except query string:

RewriteCond %{THE_REQUEST} \s[^?]*//
RewriteRule ^.*$ /$0 [R=302,L,NE]
like image 77
anubhava Avatar answered Sep 04 '25 23:09

anubhava