为什么 try_files 指令在根目录和文件名之间缺少斜杠?
Why try_files directive missing slash between root and filename?
我正在尝试将 Nginx 设置为反向代理,但也可以自己处理单个静态页面(问候语):
root /usr/share/project/;
location = / {
try_files index.html =404;
}
此配置总是 return 404。当我试图弄清楚究竟发生了什么时,我重写了 try_files 指令以使其失败:
try_files index.html index.html;
并且对我在 error.log 中看到的内容感到惊讶:
2019/05/07 17:30:39 [error] 9393#9393: *1 open() "/usr/share/projectindex.html" failed (2: No such file or directory), client: 10.25.88.214, server: , request: "GET /index.html HTTP/1.1"
如您所见,结果文件名为 projectindex.html。斜线被遗漏了。我试图在不同的地方添加 / 和 ./ 但它没有导致任何结果。
最后我通过以下方式替换了我的配置:
root /usr/share/project/;
location = / {
try_files /index.html =404;
}
location = /index.html {
}
而且有效。
我不明白第一个配置有什么问题。而且我不明白空位置的含义:
location = /index.html {
}
及其正常工作的原因。
也许有更好的方法来做同样的事情?
root
可以选择尾随 /
- 没关系,它会被忽略。
try_files
语句的 file 元素(与 Nginx 中的所有 URI 一样)需要前导 /
。有关详细信息,请参阅 this document。
例如:
root /usr/share/project;
location = / {
try_files /index.html =404;
}
location / {
proxy_pass ...;
}
之所以有效,是因为 URI 在内部被重写为 /index.html
并在 相同位置.
中处理
如果你使用index
指令,URI在内部被重写为/index.html
,Nginx将搜索匹配的位置来处理请求。在这种情况下,您需要另一个位置来处理请求。
例如:
root /usr/share/project;
location = / {
index index.html;
}
location = /index.html {
}
location / {
proxy_pass ...;
}
空位置块从外部块继承 root
的值。 index
语句无论如何都是默认值,所以严格来说,您也不需要指定该语句。请注意,index
指令的值 不需要 前导 /
。有关详细信息,请参阅 this document。
我正在尝试将 Nginx 设置为反向代理,但也可以自己处理单个静态页面(问候语):
root /usr/share/project/;
location = / {
try_files index.html =404;
}
此配置总是 return 404。当我试图弄清楚究竟发生了什么时,我重写了 try_files 指令以使其失败:
try_files index.html index.html;
并且对我在 error.log 中看到的内容感到惊讶:
2019/05/07 17:30:39 [error] 9393#9393: *1 open() "/usr/share/projectindex.html" failed (2: No such file or directory), client: 10.25.88.214, server: , request: "GET /index.html HTTP/1.1"
如您所见,结果文件名为 projectindex.html。斜线被遗漏了。我试图在不同的地方添加 / 和 ./ 但它没有导致任何结果。
最后我通过以下方式替换了我的配置:
root /usr/share/project/;
location = / {
try_files /index.html =404;
}
location = /index.html {
}
而且有效。
我不明白第一个配置有什么问题。而且我不明白空位置的含义:
location = /index.html {
}
及其正常工作的原因。
也许有更好的方法来做同样的事情?
root
可以选择尾随 /
- 没关系,它会被忽略。
try_files
语句的 file 元素(与 Nginx 中的所有 URI 一样)需要前导 /
。有关详细信息,请参阅 this document。
例如:
root /usr/share/project;
location = / {
try_files /index.html =404;
}
location / {
proxy_pass ...;
}
之所以有效,是因为 URI 在内部被重写为 /index.html
并在 相同位置.
如果你使用index
指令,URI在内部被重写为/index.html
,Nginx将搜索匹配的位置来处理请求。在这种情况下,您需要另一个位置来处理请求。
例如:
root /usr/share/project;
location = / {
index index.html;
}
location = /index.html {
}
location / {
proxy_pass ...;
}
空位置块从外部块继承 root
的值。 index
语句无论如何都是默认值,所以严格来说,您也不需要指定该语句。请注意,index
指令的值 不需要 前导 /
。有关详细信息,请参阅 this document。