**使用场景**
内网Nginx已开通外网策略,为了保证服务器出外网的安全性不修改系统DNS,此时就需要使用Nginx内置
resolver变量实现**resolver参数解释**
resolver 指令指定DNS服务器的地址,用于将域名解析为IP地址.语法规则如下
Syntax: resolver address ... [valid=time] [ipv4=on|off] [ipv6=on|off] [status_zone=zone];
Default: —
Context: http, server, location**案例演示:使用Nginx代理企业微信接口,不修改host文件以及DNS文件实现**
> 配置文件为通用配置,编译安装以及apt或yum安装皆可以使用
PING测试,默认PING没有DNS解析
root@tools-03:~# ping qyapi.weixin.qq.com
ping: qyapi.weixin.qq.com: Temporary failure in name resolution修改Nginx配置文件代理
root@tools-03:/etc/nginx/conf.d# cat nginx.conf
server {
listen 7443;
server_name localhost;
access_log logs/access_7443.log;
#DNS配置,可以写多个
resolver 192.168.21.1 valid=30s ipv6=off;
location / {
set $backend "qyapi.weixin.qq.com";
proxy_pass https://$backend;
resolver_timeout 5s;
proxy_set_header Host qyapi.weixin.qq.com; #设置域名请求头位企微地址
proxy_ssl_server_name on;
proxy_connect_timeout 60s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
}
}上述配置文件使用7443代理端口,访问qyapi.weixin.qq.com,并且DNS采用192.168.21.1
#验证配置文件并重载
root@tools-03:/etc/nginx/conf.d# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
root@tools-03:/etc/nginx/conf.d# nginx -s reload启动完毕,检查7443端口
root@tools-03:/etc/nginx/conf.d# ss -lntup|grep nginx
tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=2218,fd=5),("nginx",pid=2217,fd=5),("nginx",pid=1926,fd=5))
tcp LISTEN 0 511 0.0.0.0:7443 0.0.0.0:* users:(("nginx",pid=2218,fd=14),("nginx",pid=2217,fd=14),("nginx",pid=1926,fd=14))
tcp LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=2218,fd=6),("nginx",pid=2217,fd=6),("nginx",pid=1926,fd=6))请求测试,请求成功如下所示
root@tools-03:/etc/nginx/conf.d# curl 192.168.21.32:7443
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>查看访问日志
root@tools-03:/etc/nginx/conf.d# tail -f /usr/share/nginx/logs/access_7443.log
192.168.21.32 - - [06/Aug/2025:15:30:28 +0000] "GET / HTTP/1.1" 403 146 "-" "curl/8.9.1"> 因为没有添加企微调用接口,所以访问为403,默认情况下我们是无法解析,现在代表DNS没有问题
Nginx配置文件中set用于定义变量。配合使用resolver和set可以实现动态的DNS解析,从而根据不同的条件将请求代理到不同的后端服务器
**resolver_timeout 还可以为DNS设置超时时间**
Syntax: resolver_timeout time;
Default:
resolver_timeout 30s;
Context: http, server, location
Sets a timeout for name resolution, for example: