同一服务器部署Flask+Vite-React应用,Nginx遇404/权限拒绝错误
问题:同一服务器Nginx部署Flask+Vite-React,React应用在/portfolio路径无法正常运行
我正尝试通过Nginx在同一服务器上部署Flask与Vite-React应用,Flask应用运行正常,但仅在/portfolio路径展示的React应用无法正常工作。
当前Nginx配置
server { server_name spiralapi.dev www.spiralapi.dev; listen 80; location / { include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/server.sock; } location /portfolio { root /root/webserver/portfolio; index index.html; try_files $uri $uri/ =404; location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires max; add_header Cache-Control "public, immutable"; try_files $uri =404; } } }
说明:/portfolio是npm run build生成的dist文件夹。我接触Nginx时间不长,修改过/webserver和/webserver/portfolio的文件夹权限,但没有效果。
初始错误日志
[crit] 31634#31634: *266 stat() "/root/webserver/portfolio" failed (13: Permission denied), client: redacted, server: spiralapi.dev, request: "GET /portfolio HTTP/1.1", host: "spiralapi.dev", referrer: "https://spiralapi.dev/"
更新状态
已将/portfolio文件夹移动到共享目录/var/www,现在出现404错误,日志中无权限拒绝信息。
解决方案
1. 修正Nginx路径映射问题
当前配置的核心问题是root的使用逻辑错误:当location为子目录时,root会把location路径追加到指定路径后,导致Nginx查找错误的目录(比如访问/portfolio时,会去查找/root/webserver/portfolio/portfolio)。推荐用以下两种方式修正:
方案A:使用alias映射正确路径
修改/portfolio的location配置,适配React SPA的路由特性:
location /portfolio { alias /var/www/portfolio; # 对应你移动后的dist目录 index index.html; # 支持React客户端路由,刷新页面时重定向到index.html try_files $uri $uri/ /portfolio/index.html; location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires max; add_header Cache-Control "public, immutable"; try_files $uri =404; } }
alias会直接将/portfolio路径映射到指定目录,不会追加路径,避免拼接错误。
方案B:调整root为上级目录
如果坚持用root,需要将其设置为dist目录的上级目录:
location /portfolio { root /var/www; # Nginx会自动查找/var/www/portfolio index index.html; try_files $uri $uri/ /portfolio/index.html; location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires max; add_header Cache-Control "public, immutable"; try_files $uri =404; } }
2. 确保文件权限正确
即使移动到/var/www,也要保证Nginx运行用户(默认是www-data)有读取权限:
chown -R www-data:www-data /var/www/portfolio chmod -R 755 /var/www/portfolio
3. 验证配置并重启Nginx
先检查配置语法是否正确:
nginx -t
如果提示test is successful,重启Nginx生效:
systemctl restart nginx
内容的提问来源于stack exchange,提问作者arlo
相关产品推荐
相关产品推荐

