【问题标题】:Confirm if application is using nginx to serve static files确认应用程序是否使用 nginx 来提供静态文件
【发布时间】:2015-08-10 20:47:28
【问题描述】:

我正在使用这个tutorial - part 1,但我不确定如何测试该应用程序是否在使用 nginx 服务静态文件的情况下运行。

我有完全相同的代码。


/etc/nginx/sites-available/flask_project

server {
    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    location /static {
        alias  /home/www/flask_project/static/;
    }
}

然后:

gunicorn app:app -b localhost:8000

所有路线都运行良好。但是,如果我这样做 http://localhost:8000/static 我会看到

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

显然我应该从静态文件夹中看到带有<h1>Test!</h1> 的页面。

我做错了什么?

基本上我想知道如何配置 nginx 来提供静态文件然后确认。

-app.py
-static
   -index.html

【问题讨论】:

  • 您对localhost:8000 的请求完全绕过nginx 直接发送到gunicorn。您应该请求localhost/... 或您用于服务器的任何名称。
  • @AlexeyTen 所以,我是否正确地提供静态文件?就是这个问题。

标签: python nginx flask webserver gunicorn


【解决方案1】:

首先,对端口8000的请求完全绕过了nginx,所以这里没什么奇怪的。你应该去localhost没有端口号。

其次,您必须将此配置符号链接到 /etc/nginx/sites-enabled 并重新加载 nginx。

第三,你的静态位置不对。你有location 没有斜杠,alias 有一个。它们应该始终同时带有或不带有斜杠。在这种情况下,最好有root 指令。

server {
    root /home/www/flask_project;
    index index.html;

    location / {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location /static/ {
        # empty. Will serve static files from ROOT/static.
    }
}

【讨论】:

  • 如果我在 8000 端口运行 gunicorn,为什么要在没有端口的情况下访问 localhost?基本上你是说教程在数千次浏览后是错误的?无论如何,我的输出与您的答案相同。
  • 这是来自教程Open your browser and navigate to http://your_domain_name_or_ip_address. 没有端口,你看。而且,是的,本教程是由几乎不了解 nginx 的人编写的。
  • 对不起,我不明白。默认情况下,localhost 将使用端口 80。我明确地说要在 gunicorn 中使用 8000。如果我去本地主机,我会得到这个网页不可用
  • 端口 80 转到 nginx。任何它不知道如何直接服务的东西,它都会交给 gunicorn。当你去8000端口时,你绕过nginx,直接进入gunicorn。如果你想测试 nginx 是否正常工作,你需要使用 80 端口通过它发送你的请求。
【解决方案2】:

你应该直接提出请求http://localhost:8000/static/index.html然后你会看到响应。

但如果你想在index.html上看到默认情况下,你应该有类似的东西在conf:

location /static {
    alias  /home/www/flask_project/static/;
    try_files $uri $uri/index.html index.html;
}

【讨论】:

  • 在这种情况下,即使 nginx 停止,我也会看到响应。问题是如何检查 nginx 是否工作。
  • 不,如果 nginx 已经停止,您将看不到响应。
猜你喜欢
  • 2016-12-23
  • 2023-04-07
  • 2023-03-15
  • 1970-01-01
  • 2013-06-27
  • 2014-01-12
  • 2020-03-06
  • 2018-07-17
  • 1970-01-01
相关资源
最近更新 更多