我无法在 nginx 上正确配置位置指令

I cannot properly configure location directive on nginx

我正在学习nginx配置,我发现了一个我无法解决的问题。 我的 nginx.conf 文件中有这样的服务器上下文。

server {
        listen 192.168.1.20:80;
        server_name www.a.com;
        root /usr/share/nginx/html/a/;
        location = /extra {
                index default.html;
        }
        location = /prova {
                index index.html;
        }
}

我的本地 DNS 主机文件是

127.0.0.1   localhost
192.168.1.19    www.linuxhelp2.com
127.0.0.1    tech.com
192.168.1.20 www.a.com 
192.168.1.19 www.b.com
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

现在我预计当我只输入 www.a.com, I get an 404 error, while if I'm typing www.a.com/prova or www.a.com/extra I'm going to get the index directive html page. But when I type www.a.com I get the index.html page, while the www.a.com/extra and www.a.com/prova 时都会出现 404 错误。 index.html 和 default.html 都在 /usr/share/nginx/html/a/ 文件夹中。 我做错了什么?

Now I'm expecting that when I just type www.a.com, I get an 404 error,

URI / 将不匹配您的任何 location 定义,因此 Nginx 将使用 server 块中的语句来处理请求。 index 的默认值是 /index.html(参见 this document),结合您的 root 语句会导致 Nginx return 位于 /usr/share/nginx/html/a/index.html 的文件。

while if I'm typing www.a.com/prova or www.a.com/extra I'm going to get the index directive html page.

URI /prova 将由匹配的 location 块处理。 index 指令无关紧要,因为 URI 不以 / 结尾。 Nginx 将通过将 root 的值与 URI 连接来查找文件或目录,因此: /usr/share/nginx/html/a/prova 不存在,因此 404 状态为 returned.


如果你想让 Nginx return 一个特定的文件,你应该使用 try_files 来代替。参见 this document

例如:

root /usr/share/nginx/html/a;

location = /extra {
    try_files /default.html =404;
}
location = /prova {
    try_files /index.html =404;
}