「NGINX」- proxy_pass | 学习笔记

Module ngx_http_proxy_module/proxy_pass

配置案例

server {
    listen 80;
    server_name www.example.com;
    location / {
        proxy_pass http://127.0.0.1:8080;
    }
}

关于 proxy_pass 参数是否携带 URI 的问题

Module ngx_http_proxy_module

该处需要明确 proxy_pass http://127.0.0.1 与 proxy_pass http://127.0.0.1/ 的区别。

如果 proxy_pass 的参数携带 URI 信息,则匹配 location 的部分将被替换为 proxy_pass 指令设置。例如:

location /name/ {
    proxy_pass http://127.0.0.1/remote/;
}

curl https://example.com/name/example
curl  http://127.0.0.1/remote/example

如果 proxy_pass 参数没有携带 URL 信息,请求将直接发送到后端进行处理:

location /some/path/ {
    proxy_pass http://127.0.0.1;
}

curl https://example.com/name/example
curl http://127.0.0.1/name/example

注意事项:
1)当在 proxy_pass 中带有变量时,需要进行特殊处理,因为此时无法确定请求的 URI 信息;

域名解析行为

当直接使用域名时

对于如下配置信息:

server {
    location / {
        proxy_pass http://backends.example.com:8080;
    }
}

经过查阅相关资料(Using the Domain Name in the proxy_pass Directive):
1)在启动或重载时,Nginx 将进行 DNS 解析,而后不会再进行解析;
2)如果无法解析,将返回 host not found in upstream 错误,并记录在 error.log 日志中;
3)其域名解析是通过读取 /etc/resolv.conf 配置进行 DNS 解析;

当从变量中获取域名时

对于如下 Nginx 配置信息:

resolver 10.0.0.2 valid=10s;

server {
    location / {
        set $backend_servers backends.example.com;
        proxy_pass http://$backend_servers:8080;
    }
}

根据 Setting the Domain Name in a Variable 描述,可以得出以下结论:
1)当 TTL 后,Nginx 将重新解析域名;
2)必须配置 resolover 参数,使用 valid 控制过期;
3)不会使用 /etc/resolv.conf 配置进行 DNS 解析;

参考文献

Three ways to use nginx proxy pass and how nginx chooses the DNS server to resolve backend servers.
Using the Domain Name in the proxy_pass Directive