在Nginx反向代理配置中,使用正则表达式可以实现灵活的访问控制。以下是详细的配置方法和示例:
Nginx使用PCRE(Perl Compatible Regular Expressions)正则表达式语法:
location ~ ^/admin/.*$ {
deny all;
return 403;
}
这个配置会阻止所有以/admin/
开头的URL访问。
location ~ ^/secure/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
location / {
if ($http_user_agent ~* (wget|curl|python|java)) {
return 403;
}
proxy_pass http://backend;
}
location ~* \.(php|asp|aspx|jsp)$ {
deny all;
return 403;
}
location ~* ^/(admin|config|private)/.*\.(php|inc|conf)$ {
satisfy any;
allow 192.168.1.100;
deny all;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /downloads/ {
if ($http_referer !~* ^https?://(www\.)?example\.com/) {
return 403;
}
proxy_pass http://downloads_backend;
}
server {
listen 80;
server_name proxy.example.com;
# 阻止扫描工具
location ~* (\.git|\.svn|\.env|\.htaccess) {
deny all;
return 404;
}
# API访问控制
location ~ ^/api/v[1-3]/(users|admin)/ {
allow 10.0.0.0/8;
deny all;
proxy_pass http://api_backend;
proxy_set_header Host $host;
}
# 默认反向代理规则
location / {
proxy_pass http://backend_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
^
和$
锚定:明确匹配开始和结束位置提高效率map $uri $block_uri {
default 0;
~* "^/admin/" 1;
~* "\.(bak|old|tmp)$" 1;
}
server {
...
if ($block_uri) {
return 403;
}
...
}
nginx -t
测试配置语法/var/log/nginx/error.log
rewrite_log on;
调试重写规则通过合理使用正则表达式,可以在Nginx反向代理中实现强大而灵活的访问控制策略。