访问nginx后面的Flask应用时出现404错误

0 投票
3 回答
2771 浏览
提问于 2025-04-17 22:48

我在nginx下配置了一个虚拟主机,配置文件是这样的:

server {
        listen          80;
        server-tokens   off;
        access_log      /var/log/nginx/api.example.com.access.log;
        error_log       /var/log/nginx/api.example.com.error.log;
        index           index.html index.htm;
        server_name     api.example.com;
        autoindex       on;

        location / {
                include         uwsgi_params;
                uwsgi_pass      unix:/var/www/api.example.com/xxx.sock;
        }
}

这个文件放在 sites-availablesites-enabled 这两个文件夹里。

我也配置了 uwsgi,配置如下:

[uwsgi]
chmod-socket = 666
socket = /var/www/api.example.com/xxx.sock
processes = 5
threads = 10
master = True
module = xxx 
callable = app 
chdir = /var/www/api.example.com
venv = /home/xxx/.virtualenvs/xxx
thunder-lock = True
uid = www-data
gid = www-data
plugins = http,python
vhost = True

我能让uwsgi和nginx都正常启动,但每次访问 http://api.example.com 时,总是出现nginx的404错误。我猜它们应该是通过同一个套接字在通信,因为没有相关的错误信息出现。我还看到在 /var/www/api.example.com//var/www/api.example.com/app 目录下生成了.pyc文件,这里存放着我的视图和模型。

我该怎么调试这个问题呢?

3 个回答

1

首先,确保你的nginx安装了HttpUwsgiModule这个模块。你可以通过运行命令 "nginx -V" 来检查。这个命令会列出所有已经配置的模块。

这里有一个不错的链接 http://wiki.nginx.org/HttpUwsgiModule

1

不太确定,不过这个nginx配置可能有效。如果不行的话,可以查看一下nginx和uwsgi的日志。


server {
    listen      80;
    server_name api.xxxx.com;
    charset     utf-8;
    client_max_body_size 250M;

root /var/www/api.xxx.com/;
index index.html index.htm;

location / {
    try_files $uri $uri/ @proxy; 
}

location @proxy {
    include uwsgi_params;
    uwsgi_pass unix:/var/www/api.xxx.com/xxx.sock

    proxy_redirect     off;
    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-Host $server_name;
}

}

1

我找到了问题所在:Flask和uwsgi的应用名称不一样。当我之前说它们的名字是一样的时候,我忘记重启服务器了。

撰写回答