管理杂谈OA答疑ERP答疑教程搜索

揭秘 Nginx 中 $host变量的“三部曲”:它的值究竟由谁决定?


nginx的$host变量用于获取当前请求中的主机名(域名)

$host变量的数值

$host变量的数值按照以下优先级的顺序获取
① 请求行中的主机名 (Request Line)
           ↓ (如果不存在)
② “Host” 请求头字段 (Host Header不包含端口号)
         ↓ (如果不存在)
③ 匹配请求的 server_name (Server Name)

测试案例

nginx配置文件variable.conf
server {
    listen 8080;
    server_name test.example.com;

    location /test-host {
        default_type text/plain;
        return 200 "host variable: $host \n";
    }
}

我们分别执行下面的请求,观察$host变量的输出

请求行
curl -x http://localhost:8080 http://api.example.com/test-host
输出:host variable: api.example.com

请求头
curl -H "HOST: test1.com" http://localhost:8080/test-host 
输出: host variable: test1.com

curl -H "HOST: test1.com:8080" http://localhost:8080/test-host
输出: host variable: test1.com

无Host头(HTTP/1.0中只允许空Host)
curl -0  -H "HOST: " http://localhost:8080/test-host
host variable: test.example.com

更多精彩文章浏览...
点击右上角图标分享到朋友圈
官方网站:http://www.clicksun.cn
咨询热线:400-186-1886
服务邮箱:service@clicksun.cn