How to change request_uri in nginx proxy_pass?

2019-07-12 02:19发布

I am running a django application through gunicorn via unix socket and I have my nginx configuration which looks like this :

Current NGINX config File :

upstream django_app_server {
  server unix:/django/run/gunicorn.sock fail_timeout=0;
}

server{
    listen 80;
    server_name demo.mysite.com;
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://django_app_server;
            break;
        }
    }

}

so my django is running on a unix socket here , lets say if it was running on localhost then it has a url which looks like :

http://127.0.0.1:8000/demo/app1
http://127.0.0.1:8000/demo/notifications

Main goal

so what i want to do is , when someone visit http://demo.mysite.com/app1 they can access via proxy pass the url : http://127.0.0.1:8000/demo/app1

It would have been really easy if i would be running django on localhost tcp port and i could have easy done this and it would have worked for me :

server{
    listen 80;
    server_name demo.mysite.com;
    location / {
        proxy_pass http://127.0.0.1:8000/demo/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

}

How do i achieve this with my current nginx configurtion ?

1条回答
Anthone
2楼-- · 2019-07-12 02:55

One approach is to use rewrite ... break, for example:

location / {
    try_files $uri @proxy;
}
location @proxy {
    rewrite ^ /demo$uri break;

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://django_app_server;
}

See this document for details.

查看更多
登录 后发表回答