Nginx配置需求:在已有Django服务的域名子路径部署Vue应用
Nginx配置需求:在已有Django服务的域名子路径部署Vue应用
你好,根据你描述的环境和需求,我来帮你调整Nginx配置,让Vue应用能正常跑在founderslooking.com/app路径下。先梳理下你的当前环境:
- 服务器:Ubuntu 22.04.4 VPS
- 关键目录权限:
- 主目录
/home/founders/founders归属用户founder、组founders - Django应用位于
/home/founders/founders/back - Vue生产构建产物在
/home/founders/founders/dist,同样归属founder用户
- 主目录
- 现有服务:Django + Gunicorn + Supervisor已正常运行,主站、
/api/v1接口均可正常访问,登录功能无问题
修改后的Nginx配置(founders.conf)
你只需要在现有的Nginx配置里添加针对/app路径的处理规则即可,完整配置参考如下:
server { listen 80; server_name founderslooking.com; # 处理Vue应用的/app路径请求 location /app { root /home/founders/founders; # 优先匹配文件,不存在则返回Vue的入口index.html(适配history路由) try_files $uri $uri/ /dist/index.html; # 避免浏览器缓存旧的Vue打包文件,方便后续更新 add_header Cache-Control "no-cache"; } # 处理Django API请求 location /api { proxy_pass http://127.0.0.1:8000; # 替换成你实际的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; } # 处理Django主站的其他请求 location / { proxy_pass http://127.0.0.1:8000; # 同样替换为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; } # 处理Django静态文件(如果有单独配置需求的话) location /static { alias /home/founders/founders/back/static; # 替换成你的Django静态文件实际目录 expires 30d; add_header Cache-Control "public, max-age=2592000"; } }
关键配置说明
Vue路径处理:
root设置为/home/founders/founders,因为Vue的dist目录是它的子目录,这样Nginx会自动匹配/app请求到dist下的文件try_files规则是核心:当请求的文件不存在时,返回dist/index.html,这能保证Vue的history模式路由不会因为刷新页面出现404问题Cache-Control设置为no-cache,防止浏览器缓存旧的打包资源,后续更新Vue应用后用户能及时看到新内容
Vue项目构建前的配置:
一定要在Vue项目的vue.config.js里设置正确的publicPath,不然静态资源会加载失败:module.exports = { publicPath: '/app/' }设置后重新执行
npm run build生成新的dist目录,再上传到服务器对应路径。
后续检查步骤
- 保存修改后的Nginx配置,重启Nginx生效:
sudo systemctl restart nginx - 检查
dist目录权限,确保Nginx进程(一般是www-data用户)能读取:sudo chmod -R 755 /home/founders/founders/dist sudo chown -R founder:www-data /home/founders/founders/dist - 确认Gunicorn的监听地址和Nginx配置里的
proxy_pass完全一致,避免代理失败
做完这些,你应该就能正常访问founderslooking.com/app路径下的Vue应用了。
备注:内容来源于stack exchange,提问作者SnowCrest Digital
相关产品推荐
相关产品推荐

