1

I'm running nginx in front of my django (gunicorn) app. I want calls made to:

api.mydomain.com

to be redirected to:

localhost:8080/api

I now have this, but this obviously doesn't work:

server {
    listen     80;
    server_name  api.mydomain.com;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    location / {
        index  index.html index.htm;
        proxy_pass  http://localhost:8080/api;
    }
}

Thanks!

Nikita Popov
  • 896
  • 10
  • 19
bowlby
  • 649
  • 1
  • 8
  • 18

2 Answers2

3

You can combine proxy pass with rewrite

server {
    listen     80;
    server_name  api.mydomain.com;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    location / {
       index  index.html index.htm;
       rewrite ^(.*)$ /api$1 break;
       proxy_pass   http://localhost:8080;
    }

}
John Lemp
  • 5,029
  • 3
  • 28
  • 36
  • What should I do if I also want to serve my frontend app on 'mydomain.com'? – Nikita Popov Dec 11 '19 at 21:14
  • 1
    Just create a separate server block with the server_name mydomain.com and set the root directive to the directory containing the front end files you want to serve. – John Lemp Jan 08 '20 at 19:24
1

add a new location block like this

location ~ api.mydomain.com
{
    fastcgi_pass localhost:8080;
    fastcgi_param SCRIPT_FILENAME $document_root/Django script's folder's name/$fastcgi_script_name;
}
A human being
  • 1,220
  • 8
  • 18