Nginx:允许所有但阻止特定垃圾邮件发送者IP地址/CIDR的某些POST请求URL
如何针对选定的IP地址和CIDR阻止访问某些URL,例如example.com/blog/wp-comments-post.php?
如何允许所有人(包括IP地址1.2.3.4)访问我的博客,但阻止IP地址1.2.3.4仅访问example.com/blog/wp-comments-post.php?
如何在nginx上阻止对选定IP/CIDR的POST请求?
Nginx带有一个名为ngx_http_access_module的简单模块,用于允许或者拒绝对IP地址的访问。
您还可以使用以下方法创建配置文件并阻止某些URL。
步骤1:创建spammers.conf文件
创建一个名为/etc/nginx/spammers.conf的文件,执行:
# vi /etc/nginx/spammers.conf
您需要使用ngx_http_geo_module。
该模块创建的变量的值取决于客户端IP地址或者CIDR。
语法为:
geo $var_name {
default value1;
ip value2;
cidr value2;
}
在此示例中,块IP/CIDR 101.0.71.27、101.0.79.181、101.0.79.27、100.42.192.0/20、101.192.0.0/14和148.248.0.0/16:
# spammers.conf #
geo $spammers_ip_cidrs {
## allow all ##
default no;
## block these bad ips/cidrs/spammers ##
101.0.71.27 yes;
101.0.79.181 yes;
101.0.79.27 yes;
100.42.192.0/20 yes;
101.192.0.0/14 yes;
148.248.0.0/16 yes;
}
步骤2:更新nginx.conf
编辑nginx.conf,执行:
# vi /etc/nginx/nginx.conf
在http部分中添加以下内容:
include /etc/nginx/spammers.conf;
找到您的服务器部分,并添加以下内容以匹配您的POST请求网址:
location ~* /blog/wp-comments-post\.php$ {
if ( $spammers_ip_cidrs = yes ) {
## show default or custom forbidden page. To create black-hole use 444 code
return 403;
}
这是反向代理服务器的示例配置指令:
server {
listen 75.126.153.206:80;
server_name www.theitroad.local;
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
root /nfs/ha/root/nginx;
index index.html;
## custom error pages put them at /nfs/ha/root/nginx location ##
error_page 404 /error-page-404.html;
location /error-page-404.html {
internal;
}
error_page 403 /error-page-403.html;
location = /error-page-403.html {
internal;
}
## location section ##
location / {
proxy_pass http://backendapache;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_set_header Host www.theitroad.local;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location ~* /blog/wp-comments-post\.php$ {
if ( $spammers_ip_cidrs = yes ) {
return 403;
}
## add rest of config for matching url here ##
}
}
}
保存并关闭文件。
重新启动/重新加载nginx服务器,执行:
# service nginx reload
IP地址为75.126.153.206的访问者可以浏览整个博客,但不能发表任何评论。
他/她(很可能是机器人)将获得禁止的错误代码403。
示例403错误页面:
www.theitroad.local的自定义nginx 403页面
我如何找出垃圾邮件发送者的IP地址?
使用grep命令,如下所示:
grep '/blog/wp-comments-post.php' access_1.log
## Find all url /blog/wp-comments-post.php accessed on 30/Nov/2013 ##
## last sort is bad ##
grep '30/Nov/2013 | grep '/blog/wp-comments-post.php' /path/to/archives/access_1.log | awk '{ print }' | sort | uniq -c | sort -nr > spam.txt
输出示例:
$ cat spam.txt
22304 101.234.211.192
22133 111.235.67.111
11174 142.4.113.57
11110 192.184.37.126
4235 37.0.122.237
...
可以看到有人尝试提交评论22304次。
因此,您可以阻止所有这些IP。
您可以通过编写shell/python/perl脚本来自动化整个过程。

