3

I need send POST request to my nginx frontend server which should redirect it to upstream servers. In details:

send request to http://192.168.0.10/foo/bar/blah and URL in this request should be changed to http://192.168.0.21[22,23]:8080/foo/blah

upstream myapp {
   server 192.168.0.21:8080;
   server 192.168.0.22:8080;
   server 192.168.0.23:8080;
}

server {
    listen       80;
    server_name  localhost;

   location /foo/bar/blah/ {
      rewrite ^/foo/blah^/ /$1 break;
      proxy_pass http://myapp;
   }

but in nginx error log I see that my request changed from POST to GET and also seems didn't change URL:

"POST /foo/bar/blah HTTP/1.1" 301 185 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64)
"GET /foo/bar/blah/ HTTP/1.1" 404 117 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) 

How can I keep my POST request and change the URL?

Also about my rewrite rule

      rewrite ^/foo/blah^/ /$1 break;

I found a lot of examples for changing URL and all of them looks the same. And it is really strange for me, how this rewrite rule can change URL from /foo/bar/blah/ to /foo/blah/: in documentaion says: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

If the specified regular expression matches a request URI, URI is changed as specified in the replacement string.

but in my case request URI is /foo/bar/blah/ so regular expression /foo/blah^/ doesn't matches URI, so this rule shouldn't work. Am I right?

Would be helpful any advises.

UPD: fixed:

 location = /foo/bar/blah {
          proxy_pass http://myapp/foo/blah;
       }
2
  • Well if you POST to /foo/bar/blah, then not even location /foo/bar/blah/ should match that in the first place (no trailing slash.) // If you want the client to not change the request method on a redirect, then you need to use a 307 Temporary Redirect. But it looks like you don’t want to actually redirect the client, but pass the data on internally, so that your nginx acts as a proxy. Those are different things …
    – CBroe
    Mar 15, 2017 at 12:36
  • so how to create the right rule? I just deleted trailing slash in my rewrite and it seems starts send POST but still doesn't rewrite URI
    – Trav Erse
    Mar 15, 2017 at 13:20

1 Answer 1

7

My guess, you don't need rewrite.

location /foo/bar/ {
  proxy_pass http://myapp/;
}

This should remove /foo/bar part from proxied URL.

2
  • Thank you. I changed it to location = /foo/bar/blah { proxy_pass http://myapp/foo/blah; } and it works as expected.
    – Trav Erse
    Mar 15, 2017 at 17:45
  • @TravErse You should accept this answer so Alexey gets credit May 17, 2018 at 13:15

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.