rewrite subdomain url in nginx to backend-server

不打扰是莪最后的温柔 提交于 2019-12-12 09:19:00

问题


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!


回答1:


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

}



回答2:


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


来源:https://stackoverflow.com/questions/15579453/rewrite-subdomain-url-in-nginx-to-backend-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!