Nginx HEAD请求某些路由返回404



我很难找出为什么我的网站上的两个路由在HEAD请求上返回404,因为路由正确响应GET请求

所讨论的路由是/history/*/page/*,它们对HEAD请求都响应404。但所有其他路由对HEAD响应良好,如/about/

起初我认为它可能是sub_filterexpire off,但/路由也有它们,工作良好。

当检查日志nginx抱怨打开()没有找到文件/page/1,所以我试着删除location /块,但没有区别。

我也试过删除限制请求方法的块,但也没有什么不同。

这是我的nginx配置的核心(我已经删除了图像的位置块,https重定向,HSTS和CSP头清晰)

server {
error_page 401 403 404 /404.html;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
location ~ /page/(d+)$ {
set $htype 'page';
set $hpage $1;
set $hcanonicalurl '/$htype/$hpage';
index /index.html;
}
location ~* /history/([a-z0-9-]+)$ {
set $htype 'history';
set $hpage '$1';
set $hcanonicalurl '/$htype/$hpage';
index /index.html;
}
location = / {
set $htype 'page';
set $hpage '1';
set $hcanonicalurl '/';
index /index.html;
}
location = /index.html {
if ( $htype = '' ) {
set $htype 'page';
set $hpage 1;
set $hcanonicalurl '/';
}
sub_filter_once off;
sub_filter '%H_PAGE%' '$hcanonicalurl';
sub_filter '%H_IMAGE%' '${htype}_$hpage';
expires off;
add_header Pragma no-cache;
add_header Cache-Control "no-store";
}
location / {
try_files $uri $uri/ /index.html;
}
}

上面配置的问题是两个路由都没有以斜杠/结尾。

index指令的文档说明:

ngx_http_index_module模块处理以斜杠字符('/')结尾的请求。

或";index只适用于以斜杠&quot结尾的路由。

因此,即使位置块被正确选择,index指令也会失败,因为路由没有以斜杠结束。这将触发location /块,随后是try_file块,内部重定向到location = /index.html块,然后呈现200响应。换句话说,GET我的工作纯属运气。

那么如何修复呢?添加结束斜杠可以解决问题,但只有当我的路由以斜杠结束时,所以请求/page/1不会落在位置块下,并且使斜杠可选只会保留问题。

因此,解决这个问题的正确方法是将index指令与error_page指令交换。正如try_files的文档所解释的:

在下面的示例中,

location / {
try_files $uri $uri/ @drupal;
}
try_files指令相当于
location / {
error_page 404 = @drupal;
log_not_found off;
}

这是一个固定的版本。请注意,我对每个块使用不同的指令只是为了演示两种可能的解决方案:

server {
location ~ /page/(d+)$ {
set $htype 'page';
set $hpage $1;
set $hcanonicalurl '/$htype/$hpage';
error_page 404 = /index.html;
log_not_found off;
}
location ~* /history/([a-z0-9-]+)$ {
set $htype 'history';
set $hpage '$1';
set $hcanonicalurl '/$htype/$hpage';
try_files $uri /index.html;
}

您也可以将try_files中的$uri更改为failme或其他文件,您可以确定它永远不会存在,因此它总是属于/index重定向。