Flask和nginx在非默认静态文件位置的问题

5

我正在使用nginx(通过gunicorn)为flask应用程序提供静态文件服务。

默认静态文件夹中的静态文件可以正常工作:

<link rel="stylesheet" href="{{ url_for('static', filename='css/fa/font-awesome.min.css') }}" />

但是对于我希望仅供已登录用户访问的其他静态文件,我正在使用由Flask服务的静态文件夹:

app.register_blueprint(application_view)

application_view = Blueprint('application_view', __name__, static_folder='application_static')

在 HTML 中,我是这样调用静态文件的:

<link rel="stylesheet" href="{{ url_for('application_view.static', filename='css/main.css') }}" />

我有一个application/application_static文件夹中限制访问的静态文件。在本地Flask安装时,这很正常,但是当我部署到一个由Nginx提供/static文件的生产机器上时,我会收到“NetworkError:404 Not Found-website.com/application_static/main.css”的错误信息。

您有关于如何配置Ngix以解决此问题的想法吗?

conf.d/mysitename.conf 文件:

upstream app_server_wsgiapp {
     server localhost:8000 fail_timeout=0;
}

server {
 listen 80;
 server_name www.mysitename.com;
 rewrite ^(.*) https://$server_name$1 permanent;
}


server {
  server_name           www.mysitename.com;
  listen                443 ssl;
  #other ssl config here
  access_log            /var/log/nginx/www.mysitename.com.access.log;
  error_log             /var/log/nginx/www.mysitename.com.error.log info;
  keepalive_timeout     5;
  # nginx serve up static files and never send to the WSGI server
  location /static {
    autoindex on;
    alias /pathtositeonserver/static;
  }

  location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       if (!-f $request_filename) {
         proxy_pass http://app_server_wsgiapp;
         break;
    }
  }

  # this section allows Nginx to reverse proxy for websockets
  location /socket.io {
    proxy_pass http://app_server_wsgiapp/socket.io;
    proxy_redirect off;
    proxy_buffering 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_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
  }
}

nginx.conf:

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

展示一些nginx配置和您的应用程序的更多细节。 - iurisilvio
你的本地机器上运行的是Flask WSGI服务器还是Gunicorn?你能否也发布一下你的Nginx配置文件? - lesingerouge
@iurisilvio 抱歉我没有早点回复你,我一直在忙另一个项目。我已经添加了conf.d和nginx conf文件。我正在本地开发环境中运行打包的Flask服务器。 - Don Smythe
@lesingerouge 我正在本地开发环境中运行打包的Flask服务器。 - Don Smythe
1个回答

1

gunicorn会继续运行旧代码,除非您重新加载配置文件。

您可以停止并重新启动gunicorn,或向gunicorn进程发送HUP信号。


1
我每次部署时都会重新加载所有配置文件并停止和重启Gunicorn。 - Don Smythe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接