Nginx基于IP的URL访问控制配置方案
业务需求
开发与业务部门提出一项规则:当访问者IP不属于上海或广州办公室的外网IP段,且请求URL为 http://test.com/fuck/index.html 时,需将其永久重定向至 http://test.com/index.html 。而对于来自上海和广州办公室外网IP的访问者,访问该URL时应保持原样,不作跳转。此举旨在生产环境中实现用户隔离,确保不影响其他正常用户的服务体验。
需要注意的是,当前生产环境的Nginx未启用Lua支持,因此无法利用Lua脚本处理逻辑;同时也未安装geoip模块,故不能使用相关模块功能。解决方案必须完全依赖Nginx原生配置指令。
原始的 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;
}
在实现上述需求的过程中,遇到了一些配置上的问题。
若将 if 指令与 proxy_pass 指令同时放置在同一个 location 块内,Nginx 会忽略 if 块内的内容,直接执行 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 指令问题
像下面这样使用会报错,错误的方式:
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;
}
如果你是直接另外启动一个 location 的话,比如启动如下 location :
location /fund {
if ($remote_addr !~* "192.168.0.50|192.168.0.51|192.168.0.56") {
rewrite ^ /index.html permanent;
}
}
这样的方式也是不支持的,当用 IP 192.168.0.50 访问的时候,没有达到我们的业务需求,会报错 400
注:各位有其他好的建议,欢迎探讨。