如何通过路径路由在同一域名部署Django的app1与app2项目?
Absolutely, Nginx is perfect for this scenario—this is exactly what reverse proxying was built for! Let’s walk through how to set this up properly, plus cover some critical gotchas to keep your apps working seamlessly with shared headers/footers.
核心Nginx配置示例
Here’s a straightforward Nginx config that routes requests to https://example.com/app1/ and https://example.com/app2/ to your respective backend services:
server { listen 443 ssl; server_name example.com; # 替换为你的SSL证书路径(推荐用Let’s Encrypt免费证书) ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # 路由到app1后端服务 location /app1/ { # 替换为app1的实际后端地址(本地端口/内部IP都可以) proxy_pass http://localhost:3000/; # 传递关键请求头,确保后端应用能正确识别请求来源 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; } # 路由到app2后端服务 location /app2/ { proxy_pass http://localhost:4000/; # 同样的请求头配置,保持一致性 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; } # 可选:根路径默认跳转(比如跳转到app1) location / { return 301 /app1/; } }
关键注意事项
proxy_pass末尾的斜杠很重要:- 如果加了斜杠(比如
proxy_pass http://localhost:3000/),Nginx会把/app1/后面的路径直接拼接到后端地址(例如example.com/app1/login→http://localhost:3000/login)。 - 如果不加斜杠,会把
/app1/也带到后端路径(例如example.com/app1/login→http://localhost:3000/app1/login)。要根据你的后端应用的路径配置选择。
- 如果加了斜杠(比如
前端应用的base路径配置:
如果app1/app2是React、Vue这类单页应用,必须在构建时设置publicPath(React)或baseURL(Vue)为/app1///app2/,否则静态资源(JS/CSS)会从根路径加载,导致404。比如:- React:在
package.json中添加"homepage": "/app1/" - Vue:在
vue.config.js中设置publicPath: '/app1/'
- React:在
共享页眉/页脚的无缝体验:
确保两个应用的页眉/页脚组件样式、行为完全一致,或者考虑把公共部分抽成独立的静态资源(比如放在/static/common/路径下,用Nginx直接托管),让两个应用都引用这部分资源。
其他可选方案
如果你的架构是容器化的(Docker/Kubernetes),Traefik是个更现代化的替代选项——它能自动发现容器服务并动态配置路由,不需要手动维护Nginx配置文件。
如果偏好Apache,也可以用mod_proxy模块实现类似效果:
<VirtualHost *:443> ServerName example.com SSLEngine on SSLCertificateFile /path/to/cert.pem SSLCertificateKeyFile /path/to/privkey.pem ProxyPass /app1/ http://localhost:3000/ ProxyPassReverse /app1/ http://localhost:3000/ ProxyPass /app2/ http://localhost:4000/ ProxyPassReverse /app2/ http://localhost:4000/ </VirtualHost>
内容的提问来源于stack exchange,提问作者Rich Tier

