業務需求
業務和開發同事需要我這邊做一條規則,所有訪問 ip 為非上海、廣州 office 外網 ip,url 為http://test.com/fuck/index.html 的請求都跳轉到 http://test.com/index.html 。然后所有在上海和廣州 office 的外網 IP 訪問 http://test.com/fuck/index.html 依然還是 http://test.com/fuck/index.html。這樣就可以在生產上做隔離,不影響其他用戶的服務。
注:因為目前生產上的 Nginx 沒有做 lua 支持,所以就無法通過使用 lua 來實現該需求,也沒有安裝 geoip ,所以也無法用模塊來支持,只能原生的。
原始的 nginx 配置
01 | upstream service_test { |
02 | server 127.0.0.1:8080; |
08 | index index.html index.php; |
13 | location ~* \.(gif|jpg|jpeg|png|css|js|ico|txt|svg|woff|ttf|eot)$ |
15 | rewrite ^(.*)$ /static$1 break; |
19 | location ~* \.(html|htm)$ |
21 | rewrite ^(.*)$ /static$1 break; |
27 | include /opt/conf/nginx/proxy.conf; |
修改后的 Nginx 配置
01 | upstream service_test { |
02 | server 127.0.0.1:8080; |
08 | index index.html index.php; |
13 | location ~* \.(gif|jpg|jpeg|png|css|js|ico|txt|svg|woff|ttf|eot)$ |
15 | rewrite ^(.*)$ /static$1 break; |
19 | location ~* \.(html|htm)$ |
21 | rewrite ^(.*)$ /static$1 break; |
26 | if ($request_uri ~* "^/fuck/\w+\.html$") { |
29 | if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") { |
33 | rewrite ^ /index.html permanent; |
37 | include /opt/conf/nginx/proxy.conf; |
在實現需求的過程中出現的問題
把 if 指令 和 proxy_pass 都放在 location 下面的話,if 指令里面的內容不會執行,只會執行 proxy_pass。
2 | if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") { |
3 | rewrite ^ /index.html permanent; |
6 | include /opt/conf/nginx/proxy.conf; |
if 指令下面使用 proxy_pass 指令問題
像下面這樣使用會報錯,錯誤的方式:
1 | if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") { |
正確的方式:
1 | if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") { |
或是
1 | if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") { |
如果你是直接另外啟動一個 location 的話,比如啟動如下 location :
2 | if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") { |
3 | rewrite ^ /index.html permanent; |
這樣的方式也是不支持的,當用 IP 192.168.0.50 訪問的時候,沒有達到我們的業務需求,會報錯 400
注:各位有其他好的建議,歡迎探討。