2

Due to moving of a site, the old hoster created a redirect to the new location. However, there is a leading slash / in the redirection and the former hoster is not able/willing to fix it. So I end up with all the redirects coming in like this:

http://sub.domain.com//path/to/file.html

So I tried to remove the leading slash:

  • using mod_alias

    RedirectMatch 301 ^//(.*)$ http://sub.domain.com/$1
    
  • using mod_rewrite

    RewriteEngine on
    RewriteCond %{REQUEST_METHOD}  !=POST
    RewriteCond %{REQUEST_URI} ^(.*?)(/{2,})(.*)$
    RewriteRule . %1/%3 [R=301,L]
    

Neither works. The latter removes multiple slashes inside the path, but not at the beginning.

There are already questions regarding slash removing, but they don't solve this problem:

Does Apache somehow treat this case differently?

How do I get rid of one of the leading slashes?

Community
  • 1
  • 1
Scolytus
  • 16,338
  • 6
  • 46
  • 69

3 Answers3

4

The Problem

The point is that Apache 2 do not include leading slashes in the Requested URI, so you can't do this:

RewriteRule ^/+(.*)$ /$1 [R=301,L]

or that:

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

what workes grat for any other kind of redirects or rewrites.

The Solution

But what you can do is to use the the Apache request variable that usually looks something like this: GET /some-page HTTP/1.1

With this in mind we can do the following:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,7}\s//+(.*)\sHTTP.*$
RewriteRule ^.*$ /%1 [R=301,L]

So all leading slashes will be reduced to the one that that we need.

I tested this positive on apache 2.4

Webdesigner
  • 1,954
  • 1
  • 9
  • 16
0

This code work for me

RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.*?)/{2,}([^\s]*)
RewriteRule ^ %1/%2 [R=301,L,NE]
ghindows
  • 21
  • 2
-2

The First / is Implied

Try this:

RewriteEngine on
RewriteRule ^/(.+) $1 [R=301,L,B,NE]

Why?

To match two slashes at the beginning of the path, in htaccess, we don't need to look for two slashes—just one—because the first slash is assumed. For instance, if you wanted to match example.com/pasta, your match rule would be ^pasta$, not ^/pasta (which would only match on example.com//pasta).

This is different from httpd.conf, where you would need to specify both slashes.

Confusing, but that's how it works.

zx81
  • 41,100
  • 9
  • 89
  • 105
  • 1
    Thanks for your help, but it doesn't work... It's a bit frustrating because I don't have access to the access log... It still does not remove the leading slash. And it's not just a browser thing, `curl` shows that no redirection happens... – Scolytus Jul 02 '14 at 09:16