Nginx 0.7.65 rewrite not working for double slashes

nginxregexrewrite

Using Nginx 0.7.65, I spent a few hours trying to get what seemed to be a simple nginx rewrite to work. But the two forward slashes don't seem to work properly:

Url Before: http://www.testme.com/uploads//image.jpg

Url After: http://www.testme.com/uploads/300/image.jpg

I used the following rewrite section in my nginx.conf:

#try 1
location ~* \.jpg {
  (.*)//(image.jpg) $1/300/$2 permanent;
}

It didn't work. Any ideas how to get the nginx rewrite to properly work with two forward slashes? I tried escaping the slashes using // but that also didn't help at all. Should I try updating to nginx 0.8 and that should fix it?

I also tried these (each separately) and they didn't work. I get redirected to a 404 error page:

#try 2
location ~* \.jpg {
  rewrite "^(.*)([/]{2})image\.jpg$" $1/300/image.jpg permanent;
}

#try 3
location ~* \.jpg {
  rewrite (.+)//image\.jpg $1/300/image.jpg permanent;
}

#try 4
location ~* \.jpg {
  rewrite (.+)//(image.jpg) $1/300/$2 permanent;
}

Best Answer

The reason is rewrite module auto trim the slash when parsing the request. If you take a look at error log, you will see something like this:

[notice] 5883#0: 1 "(.+)//(image.jpg)" does not match "/uploads/image.jpg", client: 127.0.0.1, server: localhost, request: "GET /uploads//image.jpg HTTP/1.1", host: "localhost"

However, you can use $request_uri variable to keep the original request URI as received from client:

    location ~* \.jpg {
        if ($request_uri ~ "(.+)\/\/(.+\.jpg)") {
            set $folder_uri $1;
            set $file_uri $2;
            rewrite .* $folder_uri/300/$file_uri permanent;
        }
    }