简体   繁体   English

如何使用Django在Nginx中将子目录作为根服务?

[英]How to serve subdirectory as root in nginx using django?

When a user visits www.website.com I would like to server content as if the user went to www.website.com/frontend/. 当用户访问www.website.com时,我希望像访问www.website.com/frontend/一样对内容进行服务器处理。 However, I want to mask the /frontend/ part of the url so the user doesn't see it. 但是,我想屏蔽URL的/ frontend /部分,以便用户看不到它。 Can this be done? 能做到吗?

What would my rewrite rule look like? 我的重写规则是什么样的?

SOLVED: 解决了:

location = / {
    rewrite ^/$ /frontend/ last;
}

My issue was 我的问题是

location = / {} #Matches the path project.example.com only (mind there is a =)
location / {} #Matches every path (mind: there is no =)

SOLVED: 解决了:

location = / {
    rewrite ^/$ /frontend/ last;
}

My issue was 我的问题是

location = / {} #Matches the path project.example.com only (mind there is a =)
location / {} #Matches every path (mind: there is no =)

You don't need rewrite rules for this. 您不需要为此的重写规则。 Just use 只需使用

location / {
    proxy_pass http://<your_backend>/frontend/;
}

I don't think using rewrite is the perfect solution (by the way i don't think it will cover all aspects of your problem and may cause new problems) 我认为使用rewrite不是完美的解决方案(顺便说一句,我认为它不能涵盖您问题的所有方面并可能导致新问题)

The solution is as follow: 解决方法如下:

nginx config should be something like this: nginx config应该是这样的:

upstream django {
    server unix://tmp/gunicorn.sock;  //
}

server {
    listen 80;
    server_name <your_app_domain_here>;
    location /frontend {
        include uwsgi_params;
        proxy_pass http://django/;
    }
}

or if you are not using sock file, you can use http method. 或者如果您不使用sock文件,则可以使用http方法。 for example if you are running django on your localhost with port 8000, then change it to: 例如,如果您在本地主机上使用端口8000运行django,则将其更改为:

proxy_pass http://localhost:8000/;

But remember you should add this in your django settings.py . 但是请记住,您应该在django settings.py添加它。 Unless it doesn't work at all: 除非它根本不起作用:

USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = "/frontend"

By this method, you are changing base url in django. 通过这种方法,您正在django中更改基本URL。 so all django urls should start with fronted label. 因此,所有django网址都应以fronted标签开头。 Now nginx can perfectly act as a reverse proxy for your site :) 现在,nginx可以完美地充当您网站的反向代理了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM