一。什麼是代理?
當然,這裡的代理指的是 Web 代理服務,在客戶端資源請求和提供這些資源的 Web 服務之間充當中介的角色:
In computer networking, a proxy server is a server application or appliance that acts as an intermediary for requests from clients seeking resources from servers that provide those resources.
代理服務可以實現在客戶端,或者從客戶端到目標服務器中間的任意環節:
A proxy server may reside on the user's local computer, or at any point between the user's computer and destination servers on the Internet.
例如,客戶端不直接向提供目標資源的 Web 服務發起請求,而是帶上目標資源的完整 URL 去請求代理服務:
GET http://en.wikipedia.org/wiki/Proxy_server HTTP/1.1
Accept: text/html
代理服務收到之後,(由代理服務來)請求指定資源並將響應結果轉發給客戶端:
HTTP/1.1 200 OK
Content-Type: text/html; charset UTF-8
二。什麼是反向代理?
「反向」自然是相對「正向」來說的,那麼,首先要知道什麼是正向代理?
正向代理
![]()
正向代理是對外的,面向外部資源,用來從網絡上獲取各種數據:
A forward proxy is an Internet-facing proxy used to retrieve data from a wide range of sources (in most cases anywhere on the Internet).
代客戶端發出資源請求,並將響應結果返回給對應的客戶端。所以,正向代理更靠近客戶端,與客戶端的關係更密切(跟服務器關係一般,不熟)
反向代理
![]()
反向代理負責把流量根據配置規則重定向到內部服務器,外部請求並不知道內網的存在:
A reverse proxy taking requests from the Internet and forwarding them to servers in an internal network. Those making requests to the proxy may not be aware of the internal network.
反向代理是對內的,面向內部資源,用作對私有網絡上的服務器進行訪問控制和保護的前端:
A reverse proxy is usually an internal-facing proxy used as a front-end to control and protect access to a server on a private network.
所以,反向代理更靠近服務器,與服務器的關係不一般,並且只提供有限的一些資源(不像正向代理能從網絡獲取各種資源):
The reverse proxy sits closer to the web server and serves only a restricted set of websites.
並且這種代理關係對用戶來說是一定是透明的,因為用戶不知道連接的是源服務還是代理服務:
A reverse proxy (or surrogate) is a proxy server that appears to clients to be an ordinary server.
而用戶對正向代理通常是有感知的,明確知道自己正在通過代理訪問網絡資源
P.S. 除正向、反向代理之外,還有:
-
開放代理(Open proxy):面向公眾(任何人都可以訪問)的正向代理
-
匿名代理(Anonymous proxy):不公開客戶端原始 IP 地址的代理服務
-
透明代理(Transparent proxy):透傳請求和響應,不做任何修改,用作網關(Gateway)和路由器
三。如何理解「反向」?
反向代理與正向代理的工作原理完全一樣,以致於很難區分出來:
![]()
其實,關鍵區別在於,正向代理是其關聯的客戶端與所有服務器聯繫的中介,而反向代理則是其關聯的服務器與所有客戶端聯繫的中介:
Unlike a forward proxy, which is an intermediary for its associated clients to contact any server, a reverse proxy is an intermediary for its associated servers to be contacted by any client.
也就是說,正向代理代表客戶端,而反向代理代表服務器:
A proxy acts on behalf of the client(s), while a reverse proxy acts on behalf of the server(s).
從方向上看,正向代理代表客戶端請求資源,反向代理代表服務器提供資源:
[caption id="attachment_2115" align="alignnone" width="806"]
why reverse proxy named as reverse[/caption]
四。反向代理有什麼作用?
反向代理常用於以下場景:
-
加密/SSL 加速:將 SSL 加密的工作交由配備了 SSL 硬件加速器的反向代理來完成
-
負載均衡:將流量負載分發給多個 Web 服務器
-
托管/緩存靜態內容:將靜態內容(比如圖片)交由反向代理提供,分擔源站負載
-
壓縮:代理服務器能夠對資源內容進行壓縮優化,提升加載速度
-
安全防護:能夠屏蔽源服務器的存在及其特徵,結合防火牆抵禦常見 Web 攻擊
-
訪問控制:對內容進行監控/過濾,常用於工作場所、學校等
SSL 加速
對於 HTTP 服務,可以通過一層反向代理來實現 SSL 加密,具體見 [nginx HTTPS 反向代理](/articles/nginx-https 反向代理/)
負載均衡
反向代理還可以用來實現負載均衡機制,如下圖:

根據既定轉發規則(即負載均衡策略)將客戶端請求分發給各個服務器,並將其響應結果返回給對應的客戶端
P.S. 關於負載均衡的更多信息,見 負載均衡_系統設計筆記 5
暫無評論,快來發表你的看法吧