欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

nginx使用解析器动态解析域名的正确方法

最编程 2024-03-15 12:22:23
...

关于proxy_pass的配置

  • 显式创建upstream
upstream backend {
    server $host;
}
server {
    listen 80;
    server_name www.example.com;
    location / {
        proxy_pass http://backend;
    }
}

访问www.example.com proxy会将请求转发到$host

  • 隐式创建upstream
server {
    listen 80;
    server_name www.example.com;
    location / {
        proxy_pass http://$host;
    }
}

访问www.example.com upstream会利用本机DNS服务器将$host解析成IP,然后 proxy会将请求转发到解析后的IP上,如果host对应的IP发生变化,那么就需要重启nginx才能生效。

使用resolver 通过动态解析域名获取最新的 IP 地址

必须将域名设置成变量 resolver 才能在处理请求时动态解析域名。

  • 正确的用法-设置变量
server {
    listen 80;
    server_name www.example.com;
    resolver 8.8.8.8;
    location / {
        set $test test.example.com
        proxy_pass http://$test;
    }
}

访问www.example.com nginx会利用resolver 设置的DNS服务器将域名test.example.com 解析成IP, proxy会将请求转发到解析后的IP上。

  • 不生效的用法

upstream test.example.com {
    server $host;
}
server {
    listen 80;
    server_name www.example.com;
    resolver 8.8.8.8;
    location / {
        set $test test.example.com
        proxy_pass http://$test;
    }
}

访问www.example.com,upstream模块会优先查找是否定义upstream后端服务,如果有定义了就不会走DNS解析。

推荐阅读