nginx实现请求转发
反向代理适用于很多场合,负载均衡是最普遍的用法。
nginx作为目前最流行的web服务器之一,可以很方便地实现反向代理。
nginx反向代理官方文档:NGINXREVERSEPROXY
当在一台主机上部署了多个不同的web服务器,并且需要能在80端口同时访问这些web服务器时,可以使用nginx的反向代理功能:用nginx在80端口监听所有请求,并依据转发规则(比较常见的是以URI来转发)转发到对应的web服务器上。
例如有webmail,webcom以及webdefault三个服务器分别运行在portmail,portcom,portdefault端口,要实现从80端口同时访问这三个web服务器,则可以在80端口运行nginx,然后将/mail下的请求转发到webmail服务器,将/com下的请求转发到webcom服务器,将其他所有请求转发到webdefault服务器。
假设服务器域名为example.com,则对应的nginxhttp配置如下:
http{ server{ server_nameexample.com; location/mail/{ proxy_passhttp://example.com:protmail/; } location/com/{ proxy_passhttp://example.com:portcom/main/; } location/{ proxy_passhttp://example.com:portdefault; } } }
以上的配置会按以下规则转发请求(GET和POST请求都会转发):
将http://example.com/mail/下的请求转发到http://example.com:portmail/
将http://example.com/com/下的请求转发到http://example.com:portcom/main/
将其它所有请求转发到http://example.com:portdefault/
需要注意的是,在以上的配置中,webdefault的代理服务器设置是没有指定URI的,而webmail和webcom的代理服务器设置是指定了URI的(分别为/和/main/)。
如果代理服务器地址中是带有URI的,此URI会替换掉location所匹配的URI部分。
而如果代理服务器地址中是不带有URI的,则会用完整的请求URL来转发到代理服务器。
官方文档描述:
IftheURIisspecifiedalongwiththeaddress,itreplacesthepartoftherequestURIthatmatchesthelocationparameter.
IftheaddressisspecifiedwithoutaURI,oritisnotpossibletodeterminethepartofURItobereplaced,thefullrequestURIispassed(possibly,modified).
以上配置的转发示例:
http://example.com/mail/index.html->http://example.com:portmail/index.html http://example.com/com/index.html->http://example.com:portcom/main/index.html http://example.com/mail/static/a.jpg->http://example.com:portmail/static/a.jpg http://example.com/com/static/b.css->http://example.com:portcom/main/static/b.css http://example.com/other/index.htm->http://example.com:portdefault/other/index.htm