You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NGINX中在子路径配置proxy_pass的问题求助

解决Flask+Gunicorn在Nginx子目录下404的问题

核心问题分析

你的Nginx配置和Flask应用的路由前缀不匹配,导致转发后的请求无法被Flask正确识别,同时缺少必要的前缀配置让Flask知晓自身运行在子目录下。

步骤1:修正Nginx配置

修改location /chess/块的proxy_pass指令,在socket路径末尾添加斜杠/,这样Nginx会将/chess/xxx格式的请求转发为/xxx给Flask应用:

server {
    listen          80;
    server_name     127.0.0.1;
    location / {
        root /var/www/html;
    }
    location /chess/ {
        proxy_pass http://unix:/usr/share/nginx/sockets/chess.sock/; # 末尾添加斜杠
        proxy_set_header Host $http_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;
    }
}

步骤2:配置Flask应用的子目录前缀

需要让Flask知道它运行在/chess子目录下,有两种常用方式:

方式一:在Flask代码中设置

直接在应用初始化时添加配置:

from flask import Flask

app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/chess' # 添加这一行

# 你的路由代码
@app.route('/')
def index():
    return "Chess App Index"

方式二:通过环境变量启动Gunicorn

启动Gunicorn前设置SCRIPT_NAME环境变量,无需修改代码:

export SCRIPT_NAME='/chess'
gunicorn --bind unix:/usr/share/nginx/sockets/chess.sock your_app_module:app

步骤3:验证权限与服务重启

  • 检查chess.sock文件的权限,确保Nginx运行用户(通常是www-data)对该文件及所在目录有读写权限:
    sudo chown www-data:www-data /usr/share/nginx/sockets/chess.sock
    sudo chmod 660 /usr/share/nginx/sockets/chess.sock
    
  • 重启Nginx和Gunicorn服务:
    sudo systemctl restart nginx
    sudo systemctl restart your_gunicorn_service # 替换为你的Gunicorn服务名
    

测试验证

访问http://127.0.0.1/chess/,应该能正常加载Flask应用的首页,路由也能正确匹配。

内容的提问来源于stack exchange,提问作者spiff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:35:23