位置指令不起作用

Jes*_*nds 10 nginx web-server virtualhost http-status-code-404

对于我的 NGINX 服务器,我设置了一个虚拟服务器来分发静态内容。目前我正在尝试设置它以便图像具有到期日期。但是,当我为此创建一个位置指令时,一切都会导致 404。

我现在的配置是这样的:

/srv/www/static.conf

server {
    listen                          80;
    server_name                     static.*.*;

    location / {
            root                    /srv/www/static;
            deny                    all;
    }

    location /images {
            expires                 1y;
            log_not_found           off;
            root                    /srv/www/static/images;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,此文件包含在 /etc/nginx/nginx.conf 中的 http 指令中

我试图访问图像,在,让我们说...... static.example.com/images/screenshots/something.png。果然,图像也存在于/srv/www/static/images/screenshots/something.png。但是,转到上述地址不起作用,只是告诉我404 Not Found

但是,如果我删除location /images并更改location /为以下内容...

location / {
    root /srv/www/static;
}
Run Code Online (Sandbox Code Playgroud)

有用!我在这里做错了什么?

pho*_*ops 14

您的配置遵循 nginx 配置陷阱您应该在配置 nginx 之前阅读它。

要回答您的问题,您不应root在位置中定义,只需定义一次,位置标签将自动让您分配对特定目录的访问权限。

此外,不要为图像目录定义自定义根目录,而是使用try_files. 在$uri将地图/images/与目录/static/images/

试试这个配置:

server {
    listen                          80;
    server_name                     static.*.*;
    root                            /srv/www;

    location /static/ {
            deny                    all;
    }

    location /images/ {
            expires                 1y;
            log_not_found           off;
            autoindex               off;
            try_files $uri static/images$uri;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果在 `location` 中定义 `root` 是不好的做法,那么他们为什么要在 [docs/http/ngx_http_core_module.html#alias](http://nginx.org/en/docs/http/ngx_http_core_module.html#alias) 中自己完成它呢? html#别名)?(请参阅其中所说的“*最好使用 root 指令代替*”) **更正**:好的,似乎问题在于在某个位置定义主根,而不仅仅是任何根 (2认同)