1

我正在学习 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时,我会收到一个 404 错误,而如果我输入www.a.com/provawww.a.com/extra我会得到index 指令 html 页面。但是当我输入www.a.com时,我得到了 index.html 页面,而www.a.com/extrawww.a.com/prova都得到了 404 错误。index.html 和 default.html 都在 /usr/share/nginx/html/a/ 文件夹中。我究竟做错了什么?

4

1 回答 1

1

现在我期待当我输入www.a.com时,我会收到 404 错误,

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

而如果我输入www.a.com/provawww.a.com/extra,我将获得 index 指令 html 页面。

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


如果你想让 Nginx 返回一个特定的文件,你应该使用try_files。请参阅此文档

例如:

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

location = /extra {
    try_files /default.html =404;
}
location = /prova {
    try_files /index.html =404;
}
于 2020-06-26T13:17:04.137 回答