Nginx proxy and remove proxy_pass prefix

14,796

The trailing slash does this magic, take it out from proxy_pass and it should help:

server {
    listen 80;
    server_name example.com;

    location /work/ {
        proxy_pass              http://10.255.8.77:8065;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_set_header        HOST $host/work;
        proxy_read_timeout      90;
    }
  }

Let's see through the docs:

A request URI is passed to the server as follows:

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:

location /name/ {
     proxy_pass http://127.0.0.1/remote/;
} 

If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:

location /some/path/ {
     proxy_pass http://127.0.0.1; 
}
Share:
14,796
itchenyi
Author by

itchenyi

Updated on June 25, 2022

Comments

  • itchenyi
    itchenyi almost 2 years

    i want use nginx location proxy my applications

    nginx(ip address) : 10.255.1.10
    php(10.255.1.20)
    

    Ip access:

    10.255.1.20/            "access ok(200)"
    10.255.1.20/api        "access ok(200)"
    10.255.1.20/project    "access ok(200)"
    

    but i use nginx proxy access 404

    example.com/work      "access ok(200)"
    example.com/work/api  "access not found(404)"
    example.com/work/project  "access not found(404)"
    

    Nginx ConfigFile:

    server {
        listen 80;
        server_name example.com;
    
        location /work/ {
            proxy_pass              http://10.255.8.77:8065/;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto $scheme;
            proxy_set_header        HOST $host/work;
            proxy_read_timeout      90;
        }
      }
    

    i want this:

    "curl http://example.com/work          200"
    "curl http://example.com/work/api      200"
    "curl http://example.com/work/project  200" 
    

    thanks for everybody.

  • Thalis K.
    Thalis K. almost 7 years
    @anatoly Thanx for a concise, easily readable and well documented answer :)
  • David
    David over 5 years
    This doesn't seem to work if you actually want clients to be able to request the resource with an optional trailing slash. e.g. /work or /work/
  • Nikita Mendelbaum
    Nikita Mendelbaum almost 5 years
    @david for calls without trailing slash - redirect with: location = /work { return 302 /work/; }