rewrite subdomain url in nginx to backend-server

2019-04-16 11:03发布

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!

2条回答
我只想做你的唯一
2楼-- · 2019-04-16 11:39

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;
    }

}
查看更多
冷血范
3楼-- · 2019-04-16 11:59

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;
}
查看更多
登录 后发表回答