我有一个 Django 应用程序通过 Gunicorn/Uvicorn 成功运行,位于我的域的子路径下(example.com/myapp)。
Nginx vhost 如下所示:
server {
server_name example.com;
location /myapp/ {
proxy_pass http://myapp_gunicorn/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /myapp/static/ {
alias /home/www/myapp/static/;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
upstream myapp_gunicorn {
server 127.0.0.1:8002;
}
server {
if ($host = example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name example.com;
listen 80;
return 404; # managed by Certbot
}
以下是使用 Gunicorn 启动命令的 systemd 服务:
[Unit]
Description=myapp gunicorn daemon
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/home/www/myapp
ExecStart=/home/venvs/myapp/bin/gunicorn myapp.asgi:application -b 0.0.0.0:8002 -w 8 -k uvicorn.workers.UvicornWorker --log-file /home/www/myapp.log
[Install]
WantedBy=multi-user.target
继续阅读关于 Nginx 子文件夹中的 Django,我在 Django settings.py 中添加了以下设置:
FORCE_SCRIPT_NAME = '/myapp'
USE_X_FORWARDED_HOST = True
# To make Django trusts the https from the Nginx proxy
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
我可以成功访问我的应用程序及其子路径,例如https://example.com/myapp/endpoint和 Django 管理页面https://example.com/myapp/admin(成功重写为https://example.com/myapp/admin/login/?next=/admin/) 例如。
但是,当单击 Django 管理页面的验证按钮时,我被错误地重定向到基本路径(https://example.com/admin/login/?next=/admin/)。此外,我得到所有静态文件的 404,它们也在基本路径下提供https://example.com/static/xxx而不是子路径https://example.com/myapp/static/xxx,尽管我认为它在 vhost 中设置正确。
我一直在关注类似的问题(包括这个非常相似),但它对我没有帮助。
任何想法?