代理
客戶端 ====== 代理 ====== 服務端
對客戶端而言,代理是服務端;對服務端而言,代理是客戶端。這個很好理解吧,以祖孫三代關系為例,爸爸在兒子面前是爸爸,爸爸在爺爺面前是兒子。
無論是正向代理還是反向代理,代理總是在邏輯上位于客戶端和服務端之間,充當二者通訊的媒介。
代理是叫正向代理還是叫反向代理,取決于它站那一邊。站客戶端一邊的叫正向代理,站服務端一邊的叫反向代理。
正向代理
客戶端 == 代理 ========== 服務端
客戶端花錢請的代理,它替客戶端干活,以客戶端的身份與服務端通訊。這種代理叫正向代理。
因為正向代理的存在,客戶端躲在代理后面,不需要直接跟服務端通訊,具有隱藏客戶端真實身份的效果,服務端不知道客戶端的存在。
需要正向代理的場景主要有兩個,以訪問谷歌網站(服務端)為例:
- 場景1:我(客戶端)無法直接訪問服務端,需要找一個代理才能間接訪問到服務端
- 場景2:我(客戶端)可以直接訪問服務端,但我不想讓服務端知道我訪問它,需要找一個代理代替我訪問它(隱藏身份)
正向代理概念在歷史上先于反向代理出現,當時就叫代理,直到反向代理概念出現之后,為了方便區分才改叫正向代理。現在如果不明確正向反向,通常還是指正向代理。
反向代理
客戶端 ========== 代理 == 服務端
服務端花錢請的代理,它替服務端干活,以服務端的身份與客戶端通訊。這種代理叫反向代理。
由于反向代理的存在,服務端躲在代理后面,不需要直接與客戶端通訊,具有隱藏服務端真實身份的效果,客戶端不知道服務端的存在。
反向代理的主要應用場景是:
- 場景1:后臺服務器很多,不想或不方便直接面對客戶端,讓反向代理服務器頂上去,可以更靈活的設計和變更服務端網絡架構
- 場景2:在墻外建立反向代理服務器,通過它間接訪問服務端,墻只能看到我訪問反向代理,看不到訪問真實服務器(隱藏行為)
咦,根據我前面的定義,場景2里應該是正向代理啊——客戶端花錢請的代理。所以大概率需要修正:誰花錢請的代理并不重要,代理的身份才重要。下文附MDN權威定義,應該更加準確和清晰。
MDN權威定義
https://developer.mozilla.org/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling
There are two types of proxies: forward proxies (or tunnel, or gateway) and reverse proxies (used to control and protect access to a server for load-balancing, authentication, decryption or caching).
Forward proxies
A forward proxy, or gateway, or just “proxy” provides proxy services to a client or a group of clients. There are likely hundreds of thousands of open forward proxies on the Internet. They store and forward Internet services (like the DNS, or web pages) to reduce and control the bandwidth used by the group.
Forward proxies can also be anonymous and allow users to hide their IP address while browsing the Web or using other Internet services. For example, Tor routes internet traffic through multiple proxies for anonymity.
Reverse proxies
As the name implies, a reverse proxy does the opposite of what a forward proxy does: A forward proxy acts on behalf of clients (or requesting hosts). Forward proxies can hide the identities of clients whereas reverse proxies can hide the identities of servers. Reverse proxies have several use cases, a few are:
Load balancing: distribute the load to several web servers,
Cache static content: offload the web servers by caching static content like pictures,
Compression: compress and optimize content to speed up load time.