PHP中 HTTP_HOST 和 SERVER_NAME 的区别

用Nginx做的泛解析,在获取域名的时候却获取到了非预期的参数,备案下。

Nginx的配置
[conf]
server {
root /wwwroot/;
index index.php index.html index.htm;

server_name ~[a-z]+\.host\.local;

location / {
try_files $uri $uri/ /index.html;
autoindex on;

if (!-e $request_filename){
rewrite ^/(.*)$ /index.php?s=/$1 last;
}
}
}
[/conf]
获取到的Server信息
[php]
array(38) {
["USER"] => string(8) "www-data"
["HOME"] => string(8) "/var/www"
["SCRIPT_FILENAME"] => string(22) "/wwwroot/index.php"
["SCRIPT_NAME"] => string(10) "/index.php"
["DOCUMENT_URI"] => string(10) "/index.php"
["DOCUMENT_ROOT"] => string(12) "/wwwroot/"
["SERVER_PROTOCOL"] => string(8) "HTTP/1.1"
["GATEWAY_INTERFACE"] => string(7) "CGI/1.1"
["SERVER_SOFTWARE"] => string(11) "nginx/1.2.1"
["REMOTE_ADDR"] => string(9) "127.0.0.1"
["REMOTE_PORT"] => string(5) "43204"
["SERVER_ADDR"] => string(9) "127.0.0.1"
["SERVER_PORT"] => string(2) "80"
["SERVER_NAME"] => string(19) "~[a-z]+\.host\.local"
["HTTP_HOST"] => string(14) "code.host.local"
[/php]

相同点:
当满足以下三个条件时,两者会输出相同信息。
1. 服务器为80端口
2. apache的conf中ServerName设置正确
3. HTTP/1.1协议规范
不同点:
1. 通常情况:
_SERVER[“HTTP_HOST”] 在HTTP/1.1协议规范下,会根据客户端的HTTP请求输出信息。
_SERVER[“SERVER_NAME”] 默认情况下直接输出apache的配置文件httpd.conf中的ServerName值。
2. 当服务器为非80端口时:
_SERVER[“HTTP_HOST”] 会输出端口号,例如:mimiz.cn:8080
_SERVER[“SERVER_NAME”] 会直接输出ServerName值
因此在这种情况下,可以理解为:HTTP_HOST = SERVER_NAME : SERVER_PORT
3. 当配置文件httpd.conf中的ServerName与HTTP/1.0请求的域名不一致时:
httpd.conf配置如下:

ServerName mimiz.cn
ServerAlias www.mimiz.cn

客户端访问域名www.mimiz.cn
_SERVER[“HTTP_HOST”] 输出 www.mimiz.cn
_SERVER[“SERVER_NAME”] 输出 mimiz.cn

所以,在实际程序中,应尽量使用_SERVER[“HTTP_HOST”] ,比较保险和可靠。

发表评论