實驗環境:nginx 1.8.1 作為代理,地址 192.168.8.40;web1 為 CentOS 6.5 + httpd 2.2.15;web2 為 CentOS 7.2 + httpd 2.4.6。
在 8.40 上添加一段 location:
location /forum/ {
proxy_pass https://192.168.8.101/bbs/;
}
被代理端先準備好目錄與測試頁:
mkdir /web/htdocs/bbs vim /web/htdocs/bbs/index.html # 內容:<h1>192.168.8.101 bbs</h1>
此時訪問 https://192.168.8.40/forum/ 返回的就是 8.101 上的 bbs 內容。
改成正則匹配的寫法:
location ~* ^/forum {
proxy_pass https://192.168.8.101;
}
注意這種寫法不做路徑替換,因此原 /forum/ 訪問不到,需要把被代理端的 bbs 目錄改名為 forum(mv bbs forum)後才能正常打開。
經過代理後,後端看到的來源會變成代理機。先在 8.101 上調整日誌格式:
# vim /etc/httpd/conf/httpd.conf
LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
再在 nginx 側把真實地址透傳過去:
location ~* ^/forum {
proxy_pass https://192.168.8.101;
proxy_set_header X-Real-IP $remote_addr;
}
加入第二台 apache(8.39),用 upstream 定義集群:
upstream webservers {
server 192.168.8.39 weight=1;
server 192.168.8.101 weight=1;
}
server {
location / {
proxy_pass https://webservers/;
proxy_set_header X-Real-IP $remote_addr;
}
}
反覆刷新 https://192.168.8.40,即可看到請求在兩台機器之間輪轉。
先準備一個錯誤提示站點:
server {
listen 8080;
server_name localhost;
root /web/errorpages;
index index.html;
}
# mkdir /web/errorpages/ -pv
# vim index.html
# 內容:sorry, website is being repaired please wait
再為集群加上健康檢查參數和 backup 節點:
upstream webservers {
server 192.168.8.39 weight=1 max_fails=2 fail_timeout=2;
server 192.168.8.101 weight=1 max_fails=2 fail_timeout=2;
server 127.0.0.1:8080 weight=1 backup;
}
連續失敗兩次即暫時摘除該節點,兩秒後重試。關掉 web1 只剩 web2 響應,再關掉 web2 就會落到 backup 的錯誤頁。
proxy_cache_path /nginx/cache/first levels=1:2 keys_zone=first:20m max_size=1g;
server {
listen 80;
server_name localhost;
index index.html index.php;
add_header X-Via $server_addr;
add_header X-Cache "$upstream_cache_status from $server_addr";
location / {
proxy_pass https://webservers/;
proxy_set_header X-Real-IP $remote_addr;
proxy_cache first;
proxy_cache_valid 200 10m;
}
}
首次 nginx -t 會因為緩存目錄不存在而報 emerg 錯誤,手工建好即可:
# mkdir -pv /nginx/cache/first
此後響應頭中會多出 X-Via 與 X-Cache,命中狀態一目了然。
location / {
root /web/htdocs;
index index.html index.htm;
rewrite ^/bbs/(.*)$ https://192.168.8.101/forum/$1;
}
訪問 https://192.168.8.40/bbs/ 會被改寫並轉發到後端的 forum 路徑。
常見場景是幾台 web 做主從,只允許其中一台接收上傳,其餘靠同步獲取。此時可以按請求方法分流:
location / {
proxy_pass https://192.168.8.40/;
if ($request_method = "PUT"){
proxy_pass https://192.168.8.101;
}
}
被指定接收上傳的機器需要開啟 WebDAV,在 httpd.conf 的目錄段中加入 Dav on:
# curl -T /etc/fstab https://192.168.8.40 Created Resource /fstab has been created.
登錄 8.101 查看 htdocs,能看到剛上傳的 fstab 文件,說明 PUT 請求被正確導到了指定節點。