How to serve Flask static files using Nginx?

时间:2015-07-28 16:31:54

标签: python nginx flask

I've a web application with this structure:

|
|__ static
   |__style.less
   |__images
|__ myapp.py
|__ wsgi.py

I've managed to run the web application using nginx and wsgi, but the problem is that the static files are not served, i mean, the server can't find them when i go to their URL. It gives me 404.

Here's my nginx configuration file part:

 server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/public_html;
    index index.php index.html index.htm;

    server_name xxxxxxx.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location /myapp {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/public_html/myapp/myapp.sock;
}

Is there something missing?

2 个答案:

答案 0 :(得分:20)

将此添加到您的nginx配置

location ^~ /static/  {
    include  /etc/nginx/mime.types;
    root /project_path/;
}

使用应用的绝对路径替换/project_path/,您应该注意不包含静态目录以及所有内容内部/project_path/static/将在网址/static/中提供服务。

答案 1 :(得分:0)

来自How to Configure NGINX for a Flask Web Application

我发现此解决方案更好:

location /static  {
    alias /<path to project>/static;
}

当然用项目目录替换<path to project>

在此解决方案中请注意,路径中包含static!这确实对安全性有好处!减少了意外提供应用程序源文件的风险。默认情况下,flask将源文件放在<path to project>中,配置中的小错误可能会使攻击者可以看到这些源文件。