简体   繁体   中英

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/. However, I want to mask the /frontend/ part of the url so the user doesn't see it. 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)

The solution is as follow:

nginx config should be something like this:

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. for example if you are running django on your localhost with port 8000, then change it to:

proxy_pass http://localhost:8000/;

But remember you should add this in your 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. so all django urls should start with fronted label. Now nginx can perfectly act as a reverse proxy for your site :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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