31

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

42

Reference: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I needed to use 'last' flag instead of 'break' as the rewritten url is handled by a different location.
what if i want to proxy_pass to service in another port using rewrite?
6

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;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.