29

I want to use rewrite function in my nginx server.

When I try "http://www.example.com/1234", I want to rewrite "http://www.example.com/v.php?id=1234" and want to get "http://www.example.com/1234" in browser.

Here is nginx.conf file

...
  location ~ /[0-9]+ {
      rewrite "/([0-9]+)" http://www.example.com/v.php?id=$1 break;
  }
...

When I try "http://www.example.com/1234"

I want to ...

url bar in browser : http://www.example.com/1234
real url : http://www.example.com/v.php?id=1234

but I'm in trouble ...

url bar in browser : http://www.example.com/v.php?id=1234
real url : http://www.example.com/v.php?id=1234

2 Answers 2

41

Reference: http://wiki.nginx.org/HttpRewriteModule#rewrite

If the replacement string begins with http:// then the client will be redirected, and any further >rewrite directives are terminated.

So remove the http:// part and it should work:

location ~ /[0-9]+ {
        rewrite "/([0-9]+)" /v.php?id=$1 break;
}
2
  • 1
    I needed to use 'last' flag instead of 'break' as the rewritten url is handled by a different location. Oct 19, 2019 at 11:03
  • what if i want to proxy_pass to service in another port using rewrite?
    – Lei Yang
    Dec 9, 2020 at 14:42
4

In my case, I needed to use 'last' to make it work due I had other rules that I wanted to be applied:

location ~ /[0-9]+ {
    rewrite "/([0-9]+)" /v.php?id=$1 last;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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