1. 程式人生 > >nginx 代理 proxy_pass /etc/hosts

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