将静态文件服务从烧瓶更改为nginx?

时间:2015-08-03 07:47:58

标签: python nginx flask

我在nginx中运行我的烧瓶项目。这是conf文件

server {

   listen  80;
   server_name site.in;
   root /root/site-demo/;
   access_log /var/log/site/access_log;
   error_log /var/log/site/error_log;

   location / {
      proxy_pass         http://127.0.0.1:4000/;
      proxy_redirect     http://127.0.0.1:4000 http://site.in;
      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-Proto $scheme;
   }

}

当我试图将静态文件的expires部分放入conf中时,它失败了。我读到这可能是因为静态文件是由flask而不是nginx提供的。如果是这样,我应该对上面的conf文件进行哪些更改,以便nginx可以为我的项目完成静态文件服务。

根据答案我改变了conf如下。现在所有静态文件都显示403错误。

server {

   listen  80;
   server_name site.in;
   root /root/site-demo/;
   access_log /var/log/site/access_log;
   error_log /var/log/site/error_log;

   location / {
      proxy_pass         http://127.0.0.1:4000/;
      proxy_redirect     http://127.0.0.1:4000 http://site.in;
      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-Proto $scheme;
   }
   location  /static {
      alias /root/site-demo/static;
      autoindex on;
      expires max;
   } 

}

3 个答案:

答案 0 :(得分:2)

将此添加到 nginx 配置:

    location  /static {
        alias /path/to/your/static/folder;
        autoindex on;
        expires max;
    }

修改

nginx 要求整个树都是可读的,而不仅仅是你的root在nginx.conf中的起始位置。所以命令

sudo chmod -R 777 /root/site-demo/static

应解决权限问题。但是,我认为,出于安全原因,将您的网站放在Web服务器的/root目录中并不是一件好事。通常,网站会放在/var/www文件夹下。

<强> P.S。

chmod -R 777命令为所有者,组和其他人授予读取,写入和执行文件夹及其所有子文件夹中文件的权限。

答案 1 :(得分:1)

如果您在服务器或docker上运行,则应这样做:

server {
    listen 443;
    server_name sample.xx.code;
    location /{
      proxy_pass http://127.0.0.1:5000;
    }

    location  /static {
      proxy_pass http://video/static;
      expires max;
    }
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
}

答案 2 :(得分:0)

点击此处查看您的nginx配置:

/etc/nginx/sites-enabled/
/etc/nginx/sites-available/

我遇到了你描述的同样问题 注意到我有几个配置文件 只保留一个配置文件 这个网站也很有帮助: https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/