Nginx同端口反向代理部署Django与Angular双应用访问异常求助
问题根因
当前配置无法同时运行的核心原因有两个:
- Django侧:
location /back/代理到后端时,请求路径会完整带上/back/前缀,但你的Django路由没有匹配该前缀的规则,导致访问404 - Angular侧:如果配置
location /frontend/代理时,要么路径传递错误,要么Angular的基础路径base href没有对应修改,导致静态资源加载失败
完整解决方案
1. 调整Nginx配置
以下配置可实现Django走/back/前缀访问、Angular走根路径访问,支持自定义修改路径前缀:
server { listen 80; server_name www.the-patron.com the-patron.com; charset utf-8; location = /favicon.ico { access_log off; log_not_found off; } # 处理Django静态资源 location /back/staticfiles/ { root /root/thepatron/The-Patron-Backend; rewrite ^/back/staticfiles/(.*)$ /staticfiles/$1 break; } # Django Backend location /back/ { include proxy_params; # 末尾加/,Nginx会自动移除请求路径中的/back/前缀再传给Django proxy_pass http://unix:/root/thepatron/The-Patron-Backend/thepatron.sock/; } # Angular Frontend location / { proxy_pass http://localhost:4200/; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_http_version 1.1; proxy_cache_bypass $http_upgrade; } }
2. 修改Django配置
在Django项目的settings.py中添加以下配置,适配前缀访问:
# 适配/back/访问前缀,Django自动生成URL时会统一带上该前缀 FORCE_SCRIPT_NAME = '/back' # 静态资源路径对应Nginx配置 STATIC_URL = '/back/staticfiles/' # 信任当前域名避免CSRF校验报错 CSRF_TRUSTED_ORIGINS = ['http://www.the-patron.com', 'http://the-patron.com']
修改完成后执行nginx -s reload重载Nginx配置,重启Django服务即可生效。
自定义Angular访问路径的补充配置
如果需要Angular走/frontend/前缀访问,额外做两处修改即可:
- Angular开发环境启动时添加参数:
ng serve --serve-path /frontend/;生产环境打包时添加参数:ng build --base-href /frontend/ - 替换Nginx配置中Angular对应的location块:
location /frontend/ { proxy_pass http://localhost:4200/; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_http_version 1.1; proxy_cache_bypass $http_upgrade; }
内容的提问来源于stack exchange,提问作者Osama Radwan
相关产品推荐
相关产品推荐

