多个 location 语法的匹配规则:从上到下依次匹配
proxy_set_header 语法
proxy_set_header: 用来设置请求头header,Web服务器就可以由此获取到header的每个变量值。
Nginx里常见的HTTP请求头:
X-Forwarded-For: 记录代理信息,君子协议,可被伪造。格式:client, proxy1, proxy2X-Real-Ip: 一般只记录真实发出请求的客户端IPHost: 描述HTTP请求的对象,仅包括域名(IP)和端口号。HTTP/1.1请求必须包含Host头字段。
Nginx反向代理,如不使用 proxy_set_header 设置 Host 值,则默认使用 proxy_pass 里包含的 Host 信息。
语法示例:
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;Nginx常用变量
| 变量 | 示例 | 释义 |
|---|---|---|
| $host | example.com | $host 是 ngx_http_core_module模块里的变量。值 小写且 不带端口号。 |
| $http_HEADER | - | HEADER是通配符,用于捕获原始的HTTP请求头。如$http_content_type, $http_host,$http_user_agent,$http_cookie |
| $http_host | blog.csdn.net | 请求头 中 Host 字段的值 |
| $server_port | 8080 | 请求的端口号,即本机Nginx监听的端口号 |
| $proxy_add_x_forwarded_for | 36.110.25.116,220.181.38.148,101.25.48.201 | nginx把$remote_addr 变量值追加 到 X-Forwarded-For 头中形成 最终 的字符串 |
| $request | GET /uri_rel/index.html?name=tom&age=18 HTTP/1.1 | 包含$request_method, $request_uri |
| $request_uri | /uri_rel/index.html?name=tom&age=18 | 客户端发起 的原生URI:不包括 协议及主机名, 包含 查询 参数(中文也会原样输出,而不是编码后的),不包含'锚点'信息 |
| $uri | /uri_rel/index.html | 当前的请求URI,不包括任何参数 |
| $document_uri | /uri_rel/index.html | 同uri |
location /httpinfo {
return 200 '---host-"$http_host"--referer:[$http_referer]---user_agent:"$http_user_agent"--cookie($http_cookie)';
}浏览器访问 https://sub.youdomain.com:4987/httpinfo 会直接下载一个名为 httpinfo 文件,内容示例:
---host-"sub.youdomain.com:4987"--referer:[]---user_agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"--cookie(_SSID=xxxxxxxxxxxx; stay_login=0; did=xxxxxxxxxxxxxx; _CrPoSt=xxxxxxxxxxx; io=xxxxxxxxxxxx)location /httpinfo {
return 200 '---request($request)----host-"$http_host"--referer:[$http_referer]---user_agent:"$http_user_agent"--cookie($http_cookie)';
}浏览器访问 https://sub.youdomain.com:4987/httpinfo/index.html?name=tom&age=18,不会下载文件,显示纯文本:
---request(GET /httpinfo/index.html?name=tom&age=18 HTTP/1.1)----host-"sub.youdomain.com:4987"--referer:[]---user_agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"--cookie(_SSID=gssvmr35wYtamB4Q2ulJYtUcAMHxOk8SdUYNexxxxxx; stay_login=0; did=ycJ0gG73Q9I80kax49mJRCq2YPoV0L2lYi8hrq7YSi2N-7mdWW3iPfjnSEVEbPf9FMan0DWCuqOu4f3Sxxxxxx; _CrPoSt=cHJvdG9jb2w9aHR0cHM6OyBwb3J0PTU5ODc7IHBhdGhuYWxxxxxx; io=B3orJU7t4rENsAxxxxxx)nginx(三十)变量终谈 https://blog.csdn.net/wzj_110/article/details/124892581
万字总结,体系化带你全面认识Nginx https://zhuanlan.zhihu.com/p/469640256
如何通过 X-Forwarded-For 拿到用户真实 IP https://www.bilibili.com/read/cv6227572/
沙滩星空的博客