業(yè)務(wù)需求
業(yè)務(wù)和開發(fā)同事需要我這邊做一條規(guī)則,所有訪問 ip 為非上海、廣州 office 外網(wǎng) ip,url 為http://test.com/fuck/index.html 的請(qǐng)求都跳轉(zhuǎn)到 http://test.com/index.html 。然后所有在上海和廣州 office 的外網(wǎng) IP 訪問 http://test.com/fuck/index.html 依然還是 http://test.com/fuck/index.html。這樣就可以在生產(chǎn)上做隔離,不影響其他用戶的服務(wù)。
注:因?yàn)槟壳吧a(chǎn)上的 Nginx 沒有做 lua 支持,所以就無法通過使用 lua 來實(shí)現(xiàn)該需求,也沒有安裝 geoip ,所以也無法用模塊來支持,只能原生的。
原始的 nginx 配置
upstream service_test { server 127.0.0.1:8080; } server { listen 80; server_name test.com; index index.html index.php; root /tmp/test.com; error_page 404 http://test.com/404.html; error_page 502 http://test.com/502.html; error_page 500 http://test.com/500.html; location ~* \.(gif|jpg|jpeg|png|css|js|ico|txt|svg|woff|ttf|eot)$ { rewrite ^(.*)$ /static$1 break; root /tmp/test.com; # expires 1d; } location ~* \.(html|htm)$ { rewrite ^(.*)$ /static$1 break; roo /tmp/test.com; # expires 900s; } location / { proxy_pass http://service_test; include /opt/conf/nginx/proxy.conf; }
修改后的 Nginx 配置
upstream service_test { server 127.0.0.1:8080; } server { listen 80; server_name test.com; index index.html index.php; root /tmp/test.com; error_page 404 http://test.com/404.html; error_page 502 http://test.com/502.html; error_page 500 http://test.com/500.html; location ~* \.(gif|jpg|jpeg|png|css|js|ico|txt|svg|woff|ttf|eot)$ { rewrite ^(.*)$ /static$1 break; root /tmp/test.com; # expires 1d; } location ~* \.(html|htm)$ { rewrite ^(.*)$ /static$1 break; roo /tmp/test.com; # expires 900s; } set $flag 0; if ($request_uri ~* "^/fuck/\w+\.html$") { set $flag "${flag}1"; } if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") { set $flag "${flag}2"; } if ($flag = "012") { rewrite ^ /index.html permanent; } location / { proxy_pass http://service_test; include /opt/conf/nginx/proxy.conf; }
在實(shí)現(xiàn)需求的過程中出現(xiàn)的問題
把 if 指令 和 proxy_pass 都放在 location 下面的話,if 指令里面的內(nèi)容不會(huì)執(zhí)行,只會(huì)執(zhí)行 proxy_pass。
location / { if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") { rewrite ^ /index.html permanent; } proxy_pass http://service_test; include /opt/conf/nginx/proxy.conf; }
if 指令下面使用 proxy_pass 指令問題
像下面這樣使用會(huì)報(bào)錯(cuò),錯(cuò)誤的方式:
if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") { proxy_pass http://test.com/fuck; }
正確的方式:
if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") { proxy_pass http://test.com$request_uri; }
或是
if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") { proxy_pass http://test.com; }
如果你是直接另外啟動(dòng)一個(gè) location 的話,比如啟動(dòng)如下 location :
location /fund { if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") { rewrite ^ /index.html permanent; } }
這樣的方式也是不支持的,當(dāng)用 IP 192.168.0.50 訪問的時(shí)候,沒有達(dá)到我們的業(yè)務(wù)需求,會(huì)報(bào)錯(cuò) 400
注:各位有其他好的建議,歡迎探討。