How to serve subdirectory as root in nginx using d

2019-08-07 13:10发布

问题:

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 =)

回答1:

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 =)


回答2:

You don't need rewrite rules for this. Just use

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


回答3:

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 :)