是否有必要在 nginx.conf 中包含启用站点的目录?

Is it necessary to include sites-enabled directory within nginx.conf?

我正在关注 Setting up Django and your web server with uWSGI and nginx tutorial. I was stuck on part Configure nginx for your site。我尝试了在互联网上搜索的所有内容,主要是我试图修复我的配置 mysite_nginx.conf 文件,但现在看来它一直都是正确的。

这是我的配置文件 mysite_nginx.conf,它当然是从 /usr/local/etc/nginx/sites-enabled/.

链接而来的
# mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    server 127.0.0.1:8001;
}

# configuration of the server
server {
    listen                8000;
    server_name           localhost;
    charset               utf-8;
    client_max_body_size  75M;

    location /media  {
        alias /Users/username/dev/my_site/mysite/media;
    }

    location /static {
        alias /Users/username/dev/my_site/mysite/static;
    }

    location / {
        uwsgi_pass  django;
        include     /Users/username/dev/my_site/mysite/uwsgi_params;
    }
}

我遇到的问题

访问 localhost:8000/media/img.jpglocalhost:8000/static/img.jpg 总是返回 404 Not Found。在 nginx 日志中,所有请求都映射到 /usr/local/Cellar/nginx/version/html/,这是指向 /usr/local/var/www/ 的符号链接,其中存在 index.html5xx.html 文件。

我的 static/media/ 被添加到 /usr/local/Cellar/nginx/version/html/ 所以在 nginx 错误日志中我看到了对 /usr/local/Cellar/nginx/version/html/static/img.jpg.

的请求

对我有用的解决方案

nginx.conf 文件中,我包含了启用站点的路径。在此之后,我所有的请求都映射到我添加为位置别名的绝对路径,并且一切都按预期工作。

...

http {
    include       mime.types;
    include       /usr/local/etc/nginx/sites-enabled/*.conf;
    default_type  application/octet-stream;

...

问题

在我提到的教程中没有提到这个,所以我想它应该在不编辑 nginx.conf 文件的情况下工作?但这对我没有用,我是不是漏掉了什么?

首先,没有任何限制或必须遵循一种方法。您可以将所有配置放在一个 nginx.conf 中,也可以将其拆分为多个文件并包含它们,或者您可以包含目录中的特定模式。

不同的 OS 发行版可能使用不同的配置类型的默认配置设置。最常见的是 nginx.conf 使用 include site-enabled/*.conf;include conf-enabled/*.conf;

逻辑是您在 sites-availableconf-available 目录中创建您的实际配置,然后分别在 sites-enabledconf-enabled 目录中创建符号链接。所以明天如果你想禁用一个配置,而不是重命名或删除它,你只需从 xxxx-enabled 目录中删除符号链接。这只是一个约定,因此您可以更轻松地在自己的文件中管理与不同站点相关的虚拟主机。

默认情况下,这些有一些用于演示 nginx 页面的默认配置。在设置你的配置之前,你应该禁用它,这样它就不会弄乱你的配置。

现在有时 include 可能不是默认值的一部分 nginx.conf。因为您使用 brew 安装了 nginx,所以该安装中使用的配置不同。如果您检查文件,它包含以下内容

include servers/*;

所以期望是把它放在不同的地方。所以你必须知道基本配置是 nginx.conf (也可以通过从源代码编译 nginx 来更改)。然后它可以包含其他配置或选择不包含并且只在 nginx.conf 本身有一个默认服务器。在学习任何教程之前,请先阅读您的 nginx.conf 文件。