Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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;
}
share|improve this question

2 Answers 2

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;
        }
    }
share|improve this answer

Your regex appeared to be wrong, as there are only 2 capturing groups. Try this:

(.+)//(image.jpg) $1/300/$2

I also made the * a + as you probably want something to be in front of the slashes.

share|improve this answer
    
good catch! I typed the regex out incorrectly. But when I was testing the regexes on the live server I did have it set up with the correct capture groups. Thanks for the suggestion to use the + instead of the * . I'll see if that changes anything. –  John Albietz Mar 9 '11 at 19:27
    
nope doesn't work. i tried it exactly as you mentioned. –  John Albietz Mar 9 '11 at 20:53
    
have you tried giving it the absolute path for the rewrite e.g hostname/$1/300/$2 ? –  Iain Mar 14 '11 at 12:14

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.