這裏列舉幾個應用場景,下文會針對這幾個場景並結合代碼進行分析。nginx
1:proxy_pass + upstream服務器
upstream foo.example.com { server 127.0.0.1:8001; } server { listen 80; server_name localhost; location /foo { #匹配/foo結尾的域名 proxy_pass http://foo.example.com; #反向代理到foo.example.com
} }
訪問http://localhost/foo時,proxy模塊會將請求轉發到127.0.0.1的8001端口上。spa
2:只有proxy_pass,沒有upstream與resolver代理
server { listen 80; server_name localhost; location /foo { proxy_pass http://foo.example.com; } }
其實是隱式建立了upstream,upstream名字就是foo.example.com。upstream模塊利用本機設置的DNS服務器(或/etc/hosts),將foo.example.com解析成IP,訪問http://localhost/foo,proxy模塊會將請求轉發到解析後的IP上。code
若是本機未設置DNS服務器,或者DNS服務器沒法解析域名,則nginx啓動時會報相似以下錯誤:server
nginx: [emerg] host not found in upstream "foo.example.com" in /path/nginx/conf/nginx.conf:110
3:proxy_pass + resolver(變量設置域名)blog
server { listen 80; server_name localhost; resolver 114.114.114.114; location /foo { set $foo foo.example.com; proxy_pass http://$foo; } }
訪問http://localhost/foo,nginx會動態利用resolver設置的DNS服務器(本機設置的DNS服務器或/etc/hosts無效),將域名解析成IP,proxy模塊會將請求轉發到解析後的IP上get