Skip to main content
 首页 » 编程设计

python之Django 和 Flask 在同一个 nginx 服务器上

2025年01月19日36zlslch

当我访问 mysite.com 时,我目前在我的主站点上运行了一个 Djago 应用程序。但是,我希望 mysite.com/flaskapp 运行一个单独的 Flask 应用程序。我能够设置两个 nginx 站点启用的配置文件并在不同的端口上运行每个应用程序,但是由于各种原因,我想在同一个端口上运行它们(如果可能)。当我在我的 nginx 服务器文件中配置我的 flaskapp/位置时,我收到 404 错误。

这是我的主管配置文件:

[program:MYSITE] 
command=/var/www/html/MYSITE/prodenv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/MYSITE.sock MYSITE.wsgi 
directory=/var/www/html/MYSITE/public_html 
autostart=true 
autorestart=true 
stderr_logfile=/var/log/MYSITE.err.log 
stdout_logfile=/var/log/MYSITE.out.log 
 
 
[program:FLASKAPP] 
directory=/var/www/html/MYSITE/public_html/FLASKAPP/api 
command=/var/www/html/MYSITE/public_html/FLASKAPP/venv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock FLASKAPP:app 
autostart=true 
autorestart=true 
stderr_logfile=/var/log/FLASKAPP.err.log 
stdout_logfile=/var/log/FLASKAPP.out.log 

还有我的 nginx 站点启用文件:

server { 
    listen 80; 
    listen [::]:80; 
 
    server_name MYSITE; 
 
    location = /favicon.ico { access_log off; log_not_found off; } 
 
    location /static/ { 
        root /var/www/html/MYSITE/public_html; 
        expires 30d; 
    } 
 
    location / { 
        include proxy_params; 
        proxy_pass http://unix:/var/www/html/MYSITE/public_html/MYSITE.sock; 
    } 
 
    location /FLASKAPP/ { 
        include proxy_params; 
        proxy_pass http://unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock;  
    } 
} 

我写了一个函数来检查请求 url

    @app.errorhandler(404) 
    def page_not_found(error): 
         return 'This route does not exist {}'.format(request.url), 404 

哪个返回:

这条路线不存在http://MYSITE/FLASKAPP

Flask 应用程序显然可以正常工作,但路由被搞砸了。我该如何解决这个问题?

请您参考如下方法:

我想通了。我重写了 url 以删除子目录,现在一切正常:

      rewrite ^/FLASKAPP(.*)$ $1 break;