Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

http - nginx server name regex when "Host" header has a trailing dot

I've considered potential trailing hostname dot handling in two contexts in nginx, and was curious whether usage in either one is necessary for an entirely correct configuration:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, it is not necessary in either context — nginx automatically takes care of the trailing dot, both in the context of the $host variable, as well as the server_name directive, leaving only the $http_host variable with the extra dot (if present in the request).

I believe it is implemented in http/ngx_http_request.c#ngx_http_validate_host:

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

It can be verified with the following minimal config:

server {
    listen  [::]:7325;
    server_name ~^(w*).?(example.com.?)$;
    return  200 C:$2H:$hostHH:$http_hostSN:$server_name
;
}

Running the following tests against nginx/1.2.1:

%printf 'GET / HTTP/1.0
Host: head.example.com.

' | 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

' | 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
Host: head.example.com.

' | nc localhost 7325 | fgrep example
C:example.com   H:line.example.com  HH:head.example.com.    SN:~^(w*).?(example.com.?)$
%

Note that neither the regexp capture from within the server_name directive, nor the $host variable, ever has a trailing dot. As such, it is pointless to account for it in above contexts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...