Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

There is a similar question here, but the solution does not work in Apache for our site.

I'm trying to remove multiple trailing slashes from URLs on our site. I found some .htaccess code that seems to work:

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

This rule removes multiple slashes from anywhere in the URL:

http://www.mysite.com/category/accessories////
becomes
http://www.mysite.com/category/accessories/

However, it redirects once for every extra slash. So:

http://www.mysite.com/category/accessories///////
301 Redirects to
http://www.mysite.com/category/accessories//////
301 Redirects to
http://www.mysite.com/category/accessories/////
301 Redirects to
http://www.mysite.com/category/accessories////
301 Redirects to
http://www.mysite.com/category/accessories///
301 Redirects to
http://www.mysite.com/category/accessories//
301 Redirects to
http://www.mysite.com/category/accessories/

Is it possible to rewrite this rule so that it does it all in a single 301 redirect?

Also, this above directive does not work at the root level of our site:

http://www.mysite.com///// does not redirect but it should.
share|improve this question
add comment

1 Answer

If the slashes may only occur at the end of the URL, you may use this

RewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$
RewriteRule . $1/ [R=301,L]
share|improve this answer
    
I think you mean %1 (back reference to the RewriteCond pattern) in your RewriteRule, rather than $1? As it stands you will always be redirected back to the document root. Also, I'm curious as to whether (?:/) is required in the RewriteCond, can you not simply use /? –  w3d Oct 20 '12 at 15:49
    
yes, sorry force of habit in that syntax. The $1 is ok, but you can omit the (?: ) and use only / –  PatomaS Oct 21 '12 at 0:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.