nginx rewrite POST request

11,538

My guess, you don't need rewrite.

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

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

Share:
11,538
Trav Erse
Author by

Trav Erse

Updated on June 04, 2022

Comments

  • Trav Erse
    Trav Erse almost 2 years

    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;
           }
    
  • Trav Erse
    Trav Erse about 7 years
    Thank you. I changed it to location = /foo/bar/blah { proxy_pass http://myapp/foo/blah; } and it works as expected.
  • Nathan Wallace
    Nathan Wallace almost 6 years
    @TravErse You should accept this answer so Alexey gets credit