How do I set subdirectory in nginx with Django

2019-02-28 17:40发布

问题:

Environment:

  • uwsgi
  • nginx
  • django 1.3

I'm using the domain www.example.com with Django and nginx, and I want to access the Django by www.example.com/abc/ , but I don't know how to set the subdirectory.

This is the nginx conf file:

server {
        listen 80;
        server_name www.example.com;
        error_log /var/log/nginx/xxx.error_log info;

        root /home/web/abc;  # this is the directory of the django program

        location ~* ^.+\.(jpg|jpeg|png|gif|css|js|ico){
                root /home/web/abc;
                access_log off;
                expires 1h;
        }

        location ~ /abc/ {   # I want to bind the django program to the domian's subdirectory
                include uwsgi_params;
                uwsgi_pass 127.0.0.1:9000;
        }
}

When I open the website www.example.com/abc/, the django urls.py doesn't match, it only match the site like ^index$.

How can I modify the nginx location to set django to www.example.com/abc?

回答1:

According to the uWSGI on Nginx docs, you just have to pass the SCRIPT_NAME to django.

location /abc {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:9000;
    uwsgi_param SCRIPT_NAME /abc;            
}

Django will still "see" /abc, but it should deal with it so that it gets stripped off before your urls are matched. You want this to happen, if django didn't see /abc, it would generate incorrect urls for your site and none of your links would work.



回答2:

Now that uwsgi_modifier1 30 is removed in the latest versions of Nginx and uWSGI, I had to use a newer method to get it working:

uWSGI config:

[uwsgi]
route-run = fixpathinfo:

Nginx config:

location /abc {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:9000;
    uwsgi_param SCRIPT_NAME /abc; # Pass the URL prefix to uWSGI so the "fixpathinfo:" route-rule can strip it out
}

IF THAT DOESN'T FIX IT: Try installing libpcre and libpcre-dev, then reinstall uwsgi with pip install -I --no-cache-dir uwsgi. uWSGI's internal routing subsystem requires the PCRE library to be installed before uWSGI is compiled/installed. More information on uWSGI and PCRE.