为什么当请求是HEAD时,nginx不发送Content-Length头部?

我使用CURL来testing我的nginx服务器的HEAD请求。 被提供的文件是一个简单的PHP文件。

如果我使用GET

 $ curl -XGET http://test.com/phpinfo.php -I HTTP/1.1 200 OK Date: Tue, 09 Apr 2013 00:35:35 GMT Content-Type: text/html Connection: keep-alive Content-Length: 72080 

但是,如果我使用HEAD

 $ curl -XHEAD http://test.com/phpinfo.php -I HTTP/1.1 200 OK Date: Tue, 09 Apr 2013 00:37:00 GMT Content-Type: text/html Connection: keep-alive 

为什么如果请求是HEAD ,nginx会省略Content-Length头部? PHP脚本非常简单,并且不以任何特殊的方式响应HEAD

有没有我可以打开Nginx中的任何选项,以便它将发送HEADContent-Length

相关的nginx信息:

 nginx version: nginx/1.2.8 built by gcc 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1) TLS SNI support enabled configure arguments: --prefix=/usr/local/nginx-1.2.8 --with-http_ssl_module --with-http_realip_module --with-http_gzip_static_module --with-pcre --conf-path=/etc/nginx/nginx.conf --add-module=../headers-more-nginx-module-0.19rc1 

组态:

 user www-user; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; client_max_body_size 10M; sendfile on; keepalive_timeout 65; more_clear_headers "Server"; gzip on; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml; server { server_name test.com; root /www; index index.php index.html index.htm; listen 80 default_server; rewrite ^/(.*)/$ /$1 permanent; #remove trailing slash #charset koi8-r; #access_log logs/host.access.log main; include general/*.conf; #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } location ~ \.php$ { fastcgi_intercept_errors on; fastcgi_pass unix:/run/php/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } } 

nginx可能不包含HTTP HEAD请求的Content-Length响应头的一个原因是, 根据定义 ,对HEAD请求的响应在响应中不能包含消息体 (更多细节参见RFC 2616 )。

现在,HTTP服务器可以发送Content-Length: 0作为对HEAD请求的响应,但这是通过电线传送的附加信息,不一定需要。 那么我怀疑, nginx是简单地省略了一个否则冗余的响应头,因为在HEAD请求的响应中不包含Content-Length头。

希望这可以帮助!