nginx的服务器名正则表达式时,“主机”头具有后点

问题描述:

我认为在nginx的potential trailing hostname dot handling in two contexts,并很好奇的使用在任何一个是否有必要完全正确的配置:nginx的服务器名正则表达式时,“主机”头具有后点

  • server_name ~^(\w+)\.(example\.com)\.?$;

  • if ($host ~ ^(\w*)\.(example\.com)\.?$) {

不,它不是在任何情况下必须的 - nginx的自动处理的在$host variable以及server_name directive的上下文中,仅留下$http_host variable以及额外的点(如果请求中存在)。

我相信这是在http/ngx_http_request.c#ngx_http_validate_host实现:

1925 if (dot_pos == host_len - 1) { 
1926  host_len--; 
1927 } 

它可以用下面的最小配置进行验证:

server { 
    listen [::]:7325; 
    server_name ~^(\w*)\.?(example\.com\.?)$; 
    return 200 C:$2\tH:$host\tHH:$http_host\tSN:$server_name\n; 
} 

运行下面的测试针对nginx/1.2.1

%printf 'GET/HTTP/1.0\nHost: head.example.com.\n\n' | nc localhost 7325 | fgrep example 
C:example.com H:head.example.com HH:head.example.com. SN:~^(\w*)\.?(example\.com\.?)$ 
% 
%printf 'GET http://line.example.com./ HTTP/1.0\n\n' | nc localhost 7325 | fgrep example 
C:example.com H:line.example.com HH: SN:~^(\w*)\.?(example\.com\.?)$ 
% 
%printf 'GET http://line.example.com./ HTTP/1.0\nHost: head.example.com.\n\n' | nc localhost 7325 | fgrep example 
C:example.com H:line.example.com HH:head.example.com. SN:~^(\w*)\.?(example\.com\.?)$ 
% 

请注意,这两个正则表达式都不会从内部捕获server_name指令或$host变量都有一个尾部点。因此,在上述情况下解释它是毫无意义的。