网页服务器禁止IP访问

我的wordpress站点总是有很多垃圾评论。于是需要对相应的IP地址禁止访问。

我的方法是:在/etc/httpd/conf.d目录下生成后缀为多个.conf的文件,每个文件分别对一个目标文件夹进行保护。比如生成文件/etc/httpd/conf.d/deny_chenlianfu.conf,其内容为:

<Directory "/home/chenlianfu/wordpress">
    AllowOverride None
    Options MultiViews FollowSymLinks ExecCGI
    Order allow,deny
    Allow from all
    Deny from 100.42.17.90
    Deny from 101.4.136.34
    Deny from 101.91.215.188
    Deny from 101.98.247.14
    Deny from 95.85.80.227
    Deny from 95.85.80.82
    Deny from 95.85.80.86
    Deny from 98.174.90.36
</Directory>

然后重启httpd服务,使配置文件生效,从而禁止配置文件中的IP访问我的网站。

/etc/init.d/httpd restart

为了对多个文件夹进行保护,则要生成多个配置文件。我编写名为wordpress_deny_ips.pl的程序,输入含有准备禁止访问IP地址的文本文件,自动生成多个配置文件:

#!/usr/bin/perl
use strict;

my $usage = <<USAGE;
USAGE:
    perl $0 web.txt

USAGE
if (@ARGV==0){die $usage}

open IN, "/etc/httpd/conf.d/deny_chenlianfu.conf";
my %ip;
while (<IN>) {
    $ip{$1} = 1 if m/(\d+\.\d+\.\d+\.\d+)/;
}
close IN;

open IN, $ARGV[0] or die "Can not open file $ARGV[0], $!\n";
my %ip_new;
while (<IN>) {
    $ip_new{$1} = 1 if m/(\d+\.\d+\.\d+\.\d+)/;
}
close IN;

my $number = 0;
foreach (keys %ip_new) {
    if (exists $ip{$_}) {
        print STDERR "Duplicate $_\n";
    }
    else {
        $ip{$_} = 1;
        $number ++;
    }
}

my @num = keys %ip;
my $num = @num;
print STDERR "$number ips were add\n$num ips in total\n";

my $out = '
    AllowOverride None
    Options MultiViews FollowSymLinks ExecCGI
    Order allow,deny
    Allow from all
';
foreach (sort keys %ip) {
    $out .= "    Deny from $_\n";
}
$out .= "</Directory>\n";


open OUT, ">", "/etc/httpd/conf.d/deny_chenlianfu.conf" or die "Can not create file /etc/httpd/conf.d/deny_chenlianfu.conf, $!\n";
print OUT '<Directory "/home/chenlianfu/wordpress">' . $out;
close OUT;

open OUT, ">", "/etc/httpd/conf.d/deny_zhengyue.conf" or die "Can not create file /etc/httpd/conf.d/deny_zhengyue.conf, $!\n";
print OUT '<Directory "/home/zhengyue/wordpress">' . $out;
close OUT;

open OUT, ">", "/etc/httpd/conf.d/deny_wuchangsong.conf" or die "Can not create file /etc/httpd/conf.d/deny_wuchangsong.conf, $!\n";
print OUT '<Directory "/home/wuchangsong/wordpress">' . $out;
close OUT;

很多垃圾评论是全英文或含有日文。可以在主体对应的functinons.php文件中添加一些设置来禁止全英文或包含日文的评论。我在文件./wp-content/themes/twentyeleven/functions.php的尾部添加以下代码:

function refused_english_comments( $incoming_comment ) {
    $pattern = '/[一-龥]/u';
    //禁止全英文评论
    if(!preg_match($pattern, $incoming_comment['comment_content'])) {
        wp_die( "您的评论中必须包含汉字!" );
    }

    $pattern = '/[あ-んア-ン]/u';
    //禁止日文评论
    if(preg_match($pattern, $incoming_comment['comment_content'])) {
        wp_die( "评论禁止包含日文" );
    }
    return( $incoming_comment );
}
add_filter('preprocess_comment', 'refused_english_comments');

然后重启网页服务,即可生效。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据