为什么nginx中的默认配置需要location和try_files指令?

时间:2017-07-13 04:57:29

标签: http nginx configuration

我在Debian 9.0上运行Nginx 1.10.3。

这是/etc/nginx/sites-enabled/default中我的默认nginx配置的外观(为清晰起见,删除了大部分注释)。

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
}

我的文档根目录只包含默认主页的一个文件。

$ ls -l /var/www/html/
total 4
-rw-r--r-- 1 root root 867 Jun 13 02:34 index.nginx-debian.html

通过此设置,我得到了预期的响应,即主页加载 成功并尝试访问其他任何内容都会导致HTTP 404

$ sudo systemctl reload nginx
$ curl -I http://localhost/
HTTP/1.1 200 OK
Server: nginx/1.10.3
Date: Thu, 13 Jul 2017 04:47:25 GMT
Content-Type: text/html
Content-Length: 867
Last-Modified: Mon, 12 Jun 2017 21:04:50 GMT
Connection: keep-alive
ETag: "593f01f2-363"
Accept-Ranges: bytes

$ curl -I http://localhost/foo
HTTP/1.1 404 Not Found
Server: nginx/1.10.3
Date: Thu, 13 Jul 2017 04:47:31 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

$ curl -I http://localhost/foo/
HTTP/1.1 404 Not Found
Server: nginx/1.10.3
Date: Thu, 13 Jul 2017 04:47:32 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

现在我从默认配置中删除位置配置。 现在我的配置看起来没有位置配置。

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
}

通过此设置,我仍然得到类似的回复。

$ sudo systemctl reload nginx
$ curl -I http://localhost/
HTTP/1.1 200 OK
Server: nginx/1.10.3
Date: Thu, 13 Jul 2017 04:54:44 GMT
Content-Type: text/html
Content-Length: 867
Last-Modified: Mon, 12 Jun 2017 21:04:50 GMT
Connection: keep-alive
ETag: "593f01f2-363"
Accept-Ranges: bytes

$ curl -I http://localhost/foo
HTTP/1.1 404 Not Found
Server: nginx/1.10.3
Date: Thu, 13 Jul 2017 04:54:45 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

$ curl -I http://localhost/foo/
HTTP/1.1 404 Not Found
Server: nginx/1.10.3
Date: Thu, 13 Jul 2017 04:54:47 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

我的问题:

  1. 在这种情况下,locationtry_files指令的用处是什么?
  2. 您是否可以指定使用locationtry_files指令的配置产生与没有这两个指令的配置不同的结果的情况?

0 个答案:

没有答案