Skip to main content
 首页 » 编程设计

python之如何使用 Django 在 nginx 中设置子目录

2025年05月04日26qq78292959

环境:

  • uwsgi
  • nginx
  • django 1.3

我正在使用域 www.example.com使用 Django 和 nginx,我想通过 www.example.com/abc/ 访问 Django ,但我不知道如何设置子目录。

这是 nginx 配置文件:

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

当我打开网站时www.example.com/abc/ , Django urls.py不匹配,它只匹配^index$这样的网站.

如何修改 nginx 位置以将 django 设置为 www.example.com/abc ?

请您参考如下方法:

根据uWSGI on Nginx文档,您只需将 SCRIPT_NAME 传递给 django。

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

Django 仍然会“看到”/abc,但它应该处理它以便在匹配您的 url 之前将其剥离。你希望这种情况发生,如果 django 没有看到 /abc,它会为你的站点生成不正确的 url,并且你的链接都不起作用。