nginx 代理 proxy_pass /etc/hosts

在项目总遇到这样一个需求:需要将nginx作为代理使用,在nginx.conf文件中配置了proxy_pass到目标网址,如下:

proxy_pass  http://$host;(A配置)

其中域名使用了变量,并且目标域名和ip地址的对应关系保存在本机的/etc/hosts文件中,运行时报502错误,error.log 下 显示 domainname could not be resolved (3: Host not found),说明没有去读/etc/hosts(proxy_pass does not resolve DNS using /etc/hosts

但是写成下面这样就可以:

proxy_pass http://www.test.com(B配置)

说明还是有读取/etc/hosts文件

原因:

个人理解:在nginx启动时会去操作系统中的/etc/hosts 等中读取,进行解析替换,然后常驻内存中,所以B配置可行;对于A配置,由于使用了变量,所以nginx会去resolver指定的dns服务器上解析


解决方法:

 by installing dnsmasq and setting your resolver to 127.0.0.1. Basically this uses your local DNS as a resolver, but it only resolves what it knows about (among those things is your /etc/hosts) and forwards the rest to your default DNS.

参考网址:

http://stackoverflow.com/questions/8305015/when-using-proxy-pass-can-etc-hosts-be-used-to-resolve-domain-names-instead-of

http://serverfault.com/questions/240476/how-to-force-nginx-to-resolve-dns-of-a-dynamic-hostname-everytime-when-doing-p

http://blog.sina.com.cn/s/blog_57c70e190100xzsr.html


猜你喜欢

转载自blog.csdn.net/sole_cc/article/details/52263916