使用模块限制apache并发连接数和带宽
2010-03-13 14:09:06 阿炯

如何限制某个ip连接到web系统的并发数,当超过设定的并发数后就拒绝连接,解决这个问题有几个方法:
1、通过iptables来实现。
2、通过apache的mod_limitipconn模块实现,发现这两个模块很好:mod_bw和mod_limitipconn;分别是限速和限制IP连接数的模块
3、通过cband模块限制IP并发连接数和带宽,很推荐使用这种方案
4、通过mod_vhost_limit模块限制IP连接数与并发数设置
5、通过mod_qos模块限制IP连接数与并发数设置
6、通过mod_evasive模块限制IP连接数与并发数设置

这里以apache2.x为例,限制连接大致可分两种情况:单位时间并发数控制、每客户端连接数。

iptables
----------------------------------------------------------------------------
Limit HTTP Connections Per IP / Host 
Only allow 20 http connections per IP (MaxClients is set to 60 in httpd.conf): 
[Warning examples may block proxy servers] 
WARNING! Please note that large proxy servers may legitimately create a large number of connections to your server. You can skip those ips using !

/sbin/iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 -j REJECT --reject-with tcp-reset 
Skip proxy server IP 1.2.3.4 from this kind of limitations: 
/sbin/iptables -A INPUT -p tcp --syn --dport 80 -d ! 1.2.3.4 -m connlimit --connlimit-above 20 -j REJECT --reject-with tcp-reset

Limit Connections Per Second 
The following example will drop incoming connections if IP make more than 10 connection attempts to port 80 within 100 seconds
iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set 
iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 100 --hitcount 10 -j DROP

Iptables Limit the number of incoming tcp connection/syn-flood attacks 
A SYN flood is a form of denial-of-service attack in which an attacker sends a succession of SYN requests to a target’s system. This is a well known type of attack and is generally not effective against modern networks. It works if a server allocates resources after receiving a SYN, but before it has received the ACK. 

if Half-open connections bind resources on the server, it may be possible to take up all these resources by flooding the server with SYN messages. Syn flood is common attack and it can be block with following iptables rules: 
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j RETURN 

All incoming connection are allowed till limit is reached: 
-limit 1/s: Maximum average matching rate in seconds 
-limit-burst 3: Maximum initial number of packets to match

以上三条基本iptables的方法来控制访问,其对的访问的控制是非常高效的,但缺点也是易见的,较为死板;当同一属域网里对站点访问较多就是出现部分用户根本无法打开的情况。

mod_bw和mod_limitipconn
----------------------------------------------------------------------------
1:首先下载:http://dominia.org/djao/limit/mod_limitipconn-version.tar.bz2
http://svn.apache.org/repos/asf/httpd/sandbox/mod_bw/

2:编译安装
tar xjvf mod_limitipconn-0.23.tar.bz2
cd mod_limitipconn-0.23
#vi  Makefile
修改:apxs = “/usr/local/apache2/bin/apxs” # 这里是自己apache的apxs路径,加载模块
或者
#/usr/local/apache2/bin/apxs -i -c -a mod_limitipconn.c  来加载模块
make install

更多信息请参考:http://dominia.org/djao/limitipconn2.html

#tar -xvf mod_bw-0.7.tgz
#cd mod_bw
#/usr/local/apache2/bin/apxs -i -c -a /home/hto/mod_bw/mod_bw.c


将基加载进apache系统中:
LoadModule limitipconn_module modules/mod_limitipconn.so
LoadModule bw_module modules/mod_bw.so


3:修改配置文件:
1)全局控制:
在httpd.conf加上以下几行:


# 所有虚拟主机的/目录
MaxConnPerIP 3     # 每IP只允许3个并发连接
NoIPLimit image/*  # 对图片不做IP限制


# 所有主机的/mp3目录
MaxConnPerIP 1         # 每IP只允许一个连接请求   
OnlyIPLimit audio/mpeg video    # 该限制只对视频和音频格式的文件


2)局部限制,你也可以在虚拟主机的配置文件里设置IP限制,方法是完全一样:
ServerAdmin ixdba@ixdba.net
DocumentRoot /home/my
ServerName www.ixdba.net


# 所有虚拟主机的/目录
MaxConnPerIP 5         # 每IP只允许3个并发连接
NoIPLimit image/*      # 对图片不做IP限制


# 所有主机的/mp3目录
MaxConnPerIP 2         # 每IP只允许一个连接请求   
OnlyIPLimit audio/mpeg video # 该限制只对视频和音频格式的文件


ErrorLog /home/my/logs/error_log
CustomLog /home/my/logs/access_log common


3)此外必须将apache的ExtendedStatus设置为ON.在httpd.conf找到
# ExtendedStatus On
去掉前面的注释即可
配置结束,重起apache就可以生效了。
以下在httpd.conf 配置这两个模块,我的配置如下:


#需要控制的路径
MaxConnPerIP 3 #限制的线程数
NoIPLimit index.htm #对此文件不做限制


在虚拟主机配置文件下面加上:
BandwidthModule On  
ForceBandWidthModule On
Bandwidth all 10000 #限速10K
MinBandwidth all -1


mod_limitipconn和mod_bandwidth
----------------------------------------------------------------------------
Apache的使用者们开发出了mod_limitipconn和mod_bandwidth两个模块,来控制http的并发连接数和用户所能够使用的带宽,下面将以RedHat Linux来说明它们的使用方法。


一、使用mod_limitipconn限制Apache的并发连接数
mod_limitipconn可以控制每个IP地址同时连接服务器某一个目录的并发连接数,是一个非常有用的模块,并且还有支持Apache 2.x的模块下载,由于本人使用Apache 1.3版本,所以请使用2.x版本Apache的朋友到其官方网站察看具体的使用方法或参考上面所述的方法。


mod_limitipconn for Apache提供三种安装方式,分别是tar包、rpm安装文件和rpm源文件,由于rpm包只能用在 RedHat版本,并且不支持检测代理服务器,所以我们一般都使用tar包的安装方式。


我们可以确定apxs命令的路径,如我的apxs命令所在为/usr/sbin/apxs,则输入
/usr/sbin/apxs -c -i -a mod_limitipconn.c


对mod_limitipconn.c进行编译,此命令会自动在你Apache的配置文件httpd.conf中加入需要的信息,并且将生成的mod_limitipconn.so模块拷贝到Apache的模块目录。


不过为了确认此命令是否正常运作,请首先检查自己的 Apache模块目录(我的是/usr/lib/apache),看内部是否含有mod_limitipconn.so文件,没有的话请将 mod_limitipconn-0.04目录中生成的文件拷贝到此处。


刚才命令自动生成的httpd.conf可能有些错误,在我的系统中,它将LoadModule limitipconn_module modules/mod_limitipconn.so加入其中,然后请确认mod_status模块已经加载,并且在mod_status下添加了ExtendedStatus On这一行。这时我们的mod_limitipconn模块就安装完毕,下一步就是对某个目录进行并发连接数的设置了。


mod_limitipconn可以对全局和虚拟主机进行不同的限制,其语法结构都是
#所限制的目录所在,此处表示主机的根目录
MaxConnPerIP 3 #所限制的每个IP并发连接数为3个
NoIPLimit image/* #对图片不做IP限制
#所限制的目录所在,此处表示主机的/mp3目录
MaxConnPerIP 1 #所限制的每个IP并发连接数为1个
OnlyIPLimit audio/mpeg video #该限制只对视频和音频格式的文件


当对全局进行限制时,将这段代码放在httpd.conf文件没有VirtualHost的地方,若是对某个虚拟主机进行限制,请将其放在其主机定义之间,我们可以通过更改Location以及MaxConnPerIP方便的控制所限制的目录和并发连接数。最后只要重新启动Apache服务,并发连接数的限制就可以生效。


二、使用mod_bandwidth控制Apache的带宽
在下载之前,请先确认自己的Apache配置文件httpd.conf中是否含有
LoadModule bandwidth_module modules/mod_bandwidth.so
以及
AddModule mod_bandwidth.c
若是没有,请加上
LoadModule bandwidth_module libexec/apache/mod_bandwidth.so
AddModule mod_bandwidth.c


并且这两行必须分别加在相应区域的最前面,使得这个模块以最低的优先级运行。
确认后,请输入 wget ftp://ftp.cohprog.com/pub/apache/module/1.3.0/mod_bandwidth.c 将源文件下载到服务器,然后请使用apxs对其进行编译,编译方法和mod_limitipconn的基本相同,如我输入
/usr/sbin/apxs -c mod_bandwidth.c -o /usr/lib/apache(Apache的模块目录),编译程序会自动将编译成功的mod_bandwidth.so文件放到Apache的模块目录,您也可以自己确认一下,若是不正常,拷贝过去即可。


mod_bandwidth运行时需要一些特定的目录,按照默认情况,请运行以下命令创建并更改目录的权限:
mkdir /tmp/apachebw
mkdir /tmp/apachebw/link
mkdir /tmp/apachebw/master
chmod -R 777 /tmp/apachebw


然后再打开httpd.conf文件,加上以下内容
BandWidthDataDir "/tmp/apachebw/"
BandWidthModule on


这时,我们就能够对所需要限制带宽的目录进行相应的设置,此处的目录请使用服务器的绝对路径。如我们想限制服务器/home/www/ssite/download/soft目录的下载速度,也就是限制网址http://download.ssite.org/soft目录下软件的下载速度,则为httpd.conf文件增加以下内容
BandWidth ssite.org 0 #来自ssite.org的下载不受速度限制
BandWidth 210.51.21 0 #来自210.51.21网段的下载不受速度限制
BandWidth all 327680 #来自其它网段的速度都限制为327680Byte,即30KB/s


设置完毕后,重新启动Apache服务,即可生效。
mod_bandwidth还有许多其它有用的参数,如在中间加上MaxConnection 120则可以限制某个目录的最多连接数,当超过指定连接数时,拒绝新的连接,此参数与mod_limitipconn模块结合可以控制某个目录的最多连接人数。


mod-cband
----------------------------------------------------------------------------
发起大量连接,占用系统资源与带宽,而又不释放连接,使得真正要访问的用户速度很慢,于是给apache加上了同IP并发数限制与带宽限制。
在 apache1.x下,需要mod_limitipconn和mod_bandwidth俩模块配合才能实现,而在apache2下,只需要 libapache2-mod-cband就完成以上两个模块的功能,cband模块主页:http://cband.linux.pl
“mod_cband is an Apache 2 module provided to solve the problem of limiting users' and virtualhosts' bandwidth usage. The current versions can set virtualhosts' and users' bandwidth quotas, maximal download speed (like in mod_bandwidth), requests-per-second speed and the maximal number of simultanous IP connections (like in mod_limitipconn)


I advise using mod_cband by hosting companies, which would like to limit data transfer for their users, such as "10Gb of traffic per month". There already exists the mod_curb module, which can limit data transfers, but it doesn't work with virtualhosts and Apache 2, so I wrote my own module fully compatible with Apache 2 API and supporting per-user and per-virtualhost bandwidth limiting”


这里介绍的安装方法适用于Debian系列系统,
采用apt-get install libapache2-mod-cband即可完成安装;
在debian 系统中,/etc/apache2下是其配置的相关文件,可用模块存放在/etc/apache2/mods-available/中,而启用模块只需要把/etc/apache2/mods-available/中的模块链接到/etc/apache2/mods-enabled即可。要想cband生效,需要进行如下工作:
#a2enmod cband


如果要限制默个虚拟站点,那么修改/etc/apache2/sites-enabled中的站点配置文件,如果要对所有站点进行限制,那么修改cband.conf文件:
/etc/apache2/sites-enabled中的配置文件,内容类似以下: 


DocumentRoot /var/www/xyz.org/
ServerName xyz.org
CustomLog /var/log/apache2/xyz.org.access combined
ErrorLog /var/log/apache2/xyz.org.access.error
RewriteEngine On
RewriteOptions inherit


# Maximal 1024kbps speed for this virtualhost
# Maximal 10 requests per second for this virtualhost
# Maximal 30 open connections for this virtualhost
CBandSpeed 10024 600 300


# Maximal 10kB/s speed, 3 requests/s and 2 open connections for any remote client
CBandRemoteSpeed 256kb/s 6 6


# Maximal 20kB/s speed, 2 requests/s and 3 open connections for remote
# clients from class googlebot_class :P
CBandClassRemoteSpeed googlebot_class 20kb/s 2 3


说明: CBandSpeed 10024 600 300 #CBandSpeed 限制 xyz.org 的虚拟主机的总访问速度为 10024kbps, 最大每秒 600个请求和最大每秒 300个连接.
CBandRemoteSpeed 256kb/s 6 6 #CBandRemoteSpeed 限制 xyz.org 的虚拟主机的任何个人的访问速度为每秒 256kb, 最大每秒 6个请求和最大每秒 6个连接.


其他说明:
1、在apache2.conf中添加CBandScoreFlushPeriod 1和CBandRandomPulse On可改善cband模块性能
2、安装好之后,可通过http://xyz.org/cband-status适时查看各个IP的连接情况,进行系统健康
3、由于debian5系统提供的libapache2-mod-cband模块无法使用,需要自行编译。


mod_vhost_limit
----------------------------------------------------------------------------
通过mod_vhost_limit模块限制IP连接数与并发数设置


下载模块:
到官方网址:http://www.nowhere-land.org/programs/mod_vhost_limit/下载模块


安装:
apxs -c mod_vhost_limit.c -o /path/to/libexec/mod_vhost_limit.so


在 httpd.conf 加入:
LoadModule vhost_limit_module libexec/mod_vhost_limit.so
AddModule mod_vhost_limit.c


配置:
MaxClients 150
ExtendedStatus On
NameVirtualHost *


ServerName       server1
DocumentRoot     /some/where/1
MaxVhostClients  100


ServerName       server2
DocumentRoot     /some/where/2
MaxVhostClients  30


ServerName       server3
DocumentRoot     /some/where/3


其中: server1 被限制为 100 个并发线程数。 server2 被限制为 30 个并发线程数。 server3 没有被限制。
注:需 mod_status 的 ExtendedStatus On 支持!


mod_qos
----------------------------------------------------------------------------
Defend slowloris DDoS With mod_qos(使用mod_qos模块防范如slowloris这样的DDoS攻击)
Slowloris is designed so that a single machine (probably a Linux/UNIX machine since Windows appears to limit how many sockets you can have open at any given time) can easily tie up a typical web server or proxy server by locking up all of it's threads as they patiently wait for more data. Some servers may have a smaller tolerance for timeouts than others, but Slowloris can compensate for that by customizing the timeouts. There is an added function to help you get started with finding the right sized timeouts as well. As a side note, Slowloris does not consume a lot of resources so modern operating systems don't have a need to start shutting down sockets when they come under attack, which actually in turn makes Slowloris better than a typical flooder in certain circumstances. Think of Slowloris as the HTTP equivalent of a SYN flood.


I recently had to defend a live attack with slowloris-dos from a botnet. The load-impact is very low but http quits serving very fast. A quick approach was to mangle with timeout settings, wich is fine to defend a single attacker but leads into new issues (ie. large NAT on client-side).


mod_qos gives some fine-grained opportunities to scale the number of used connections and to defend an attack according to bandwidth limits. Unfortunately it is only available as source-package and there are many possible settings, wich might be hard to setup for this special case. So I provide the way that helped me.


1. Get the source, build & install
mod_qos is available from sourceforge (http://sourceforge.net/projects/mod-qos/). You will find documentation here http://mod-qos.sourceforge.net/.


cd /tmp/
wget http://downloads.sourceforge.net/sourceforge/mod-qos/mod_qos-9.24-src.tar.gz?use_mirror=freefr
tar xvfz mod_qos-9.24-src.tar.gz


You might want to copy & paste the direct link from sourceforge. As we want to compile mod_qos by use of apxs, we need to install the appropriate dev package and gcc of course, ie:
apt-get install apache2-threaded-dev gcc


Now build & install
cd mod_qos-9.24/apache2/
apxs2 -i -c mod_qos.c


If everything worked fine you'll get something like this:
---------------------------------
Libraries have been installed in:
/usr/lib/apache2/modules
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
- add LIBDIR to the `LD_LIBRARY_PATH' environment variable
during execution
- add LIBDIR to the `LD_RUN_PATH' environment variable
during linking
- use the `-Wl,--rpath -Wl,LIBDIR' linker flag
- have your system administrator add LIBDIR to `/etc/ld.so.conf'
See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------
chmod 644 /usr/lib/apache2/modules/mod_qos.so


2. Now configure and activate
Go to /etc/apache2/mods-available and add a qos.load and qos.conf file
cd /etc/apache2/mods-available/
vi qos.load

LoadModule qos_module /usr/lib/apache2/modules/mod_qos.so

vi qos.conf
## QoS Settings

# handles connections from up to 100000 different IPs
# 可处理来自100000 个不同ip地址
QS_ClientEntries 100000
# will allow only 50 connections per IP
# 每ip仅多50个连接
QS_SrvMaxConnPerIP 50
# maximum number of active TCP connections is limited to 256
# 将活动的TCP连接数限制在256
MaxClients              256 
# disables keep-alive when 70% of the TCP connections are occupied:
# 当在达到规定的活动连接数的70%时禁用'keep-alive'属性
QS_SrvMaxConnClose      180
# minimum request/response speed (deny slow clients blocking the server, ie. slowloris keeping connections open without requesting anything):
# 最小的请求/响应速度
QS_SrvMinDataRate       150 1200
# and limit request header and body (carefull, that limits uploads and post requests too):
# 限制请求的头和内容(注意,这会影响上传和请求)
# LimitRequestFields      30
# QS_LimitRequestBody     102400

Now you need to enable the module and restart apache:
a2enmod qos
/etc/init.d/apache2 restart


If you are able to get the server-status by https://__yourserver__/server-status, you'll find mod_qos enabled and working by giving a statistical summary, like this:
mod_qos 9.24
viewer settings
client ip connections     

__yourserver__:0 (base)
connections
free ip entries
255
current connections
1
client ip connections
current
aaa.bbb.ccc.ddd     1
connection settings
max connections
-
max connections with keep-alive
180
max connections per client ip
50
min. data rate (bytes/sec) (min/max/current)
150/1200/154


__yourserver1__:443 (virtual)
uses base server settings


__yourserver1__:80 (virtual)
uses base server settings


__yourserver2__:443 (virtual)
uses base server settings


__yourserver2__:80 (virtual)
uses base server settings


mod_evasive
----------------------------------------------------------------------------
mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection and network management tool, and can be easily configured to talk to ipchains, firewalls, routers, and etcetera. mod_evasive presently reports abuses via email and syslog facilities.


Detection is performed by creating an internal dynamic hash table of IP Addresses and URIs, and denying any single IP address from any of the following:

Requesting the same page more than a few times per second
Making more than 50 concurrent requests on the same child per second
Making any requests while temporarily blacklisted (on a blocking list)


This method has worked well in both single-server script attacks as well as distributed attacks, but just like other evasive tools, is only as useful to the point of bandwidth and processor consumption (e.g. the amount of bandwidth and processor required to receive/process/respond to invalid requests), which is why it’s a good idea to integrate this with your firewalls and routers for maximum protection.


This module instantiates for each listener individually, and therefore has a built-in cleanup mechanism and scaling capabilities. Because of this per-child design, legitimate requests are never compromised (even from proxies and NAT addresses) but only scripted attacks. Even a user repeatedly clicking on ‘reload’ should not be affected unless they do it maliciously. mod_evasive is fully tweakable through the Apache configuration file, easy to incorporate into your web server, and easy to use.


Installation
apt-get install libapache2-mod-evasive libapache-mod-security


Create a new directory for your log files:
mkdir /var/log/apache/mod_evasive


Set ownership to Apache:
chown www-data:www-data /var/log/apache2/mod_evasive/


Create a configuration file in your conf.d directory all files in this folder gets read by Apache Server
nano /etc/apache2/conf.d/mod_evasive.conf


Add the following to your configuration file:
DOSHashTableSize 3097
 DOSPageCount 2
 DOSSiteCount 50
 DOSPageInterval 1
 DOSSiteInterval 1
 DOSBlockingPeriod 10
 DOSLogDir /var/log/apache2/mod_evasive
 DOSWhitelist 127.0.0.1

Here is what settings stand for:
DOSHashTableSize is the size of the hash table that is created for the IP addresses monitored.
DOSPageCount is the number of pages allowed to be loaded for the DOSPageInterval setting. In our case, 2 pages per 1 second before the IP gets flagged.
DOSSiteCount is the number of objects (ie: images, style sheets, javascripts, SSI, etc) allowed to be accessed in theDOSSiteInterval second. In our case, 50 objects per 1 second.
DOSPageInterval is the number of seconds the intervals are set for DOSPageCount
DOSSiteInterval is the number of seconds the intervals are set for DOSSiteCount
DOSBlockingPeriod is the number of seconds the IP address will recieve the Error 403 (Forbidden) page when they have been flagged.


Enable the modules and restart Apache Server:
a2enmod mod-evasive
a2enmod mod-security
/etc/init.d/apache2 restart


mod_evasive的特性
mod_evasive通过对来访IP地址和访问URI建立内部动态哈希表来检测是否有攻击,如果有如下的行为将拒绝该IP的访问:
1. 每秒对同一页面的请求数超过平常(原文:Requesting the same page more than a few times per second)。
2. 每秒同一个子进程有超过50次的并发请求。
3. 临时被拒绝(在blacklist中)的时候还不断进行请求。


mod_evasive可以非常方便的和防火墙、路由器等进行整合,进一步提高抗拒绝服务的能力。和别的防攻击工具一样,mod_evasive同样收到带宽、系统处理能力等因素的影响,所以要想应对大规模的攻击,最好的方式就是把mod_evasive和防火墙和路由器进行整合,而不是简单的安装成为独立的Apache模块。


编译安装
# tar -zxvf mod_evasive_1.10.tar.gz
# cd mod_evasive
# /usr/local/apache/bin/apxs -i -a -c mod_evasive20.c


说明:动态编译apache, 这里编译mod_evasive20.c是应对2.X版本的apache,如果是1.x版本的apache则编译mod_evasive.c就行了


----------------------------------------------------------------------
chmod 755 /usr/local/apache/modules/mod_evasive20.so
[activating module `evasive20' in /etc/apache2/httpd.conf]


进行一些参数的定制配置,添加如下参数:
<IfModule mod_evasive20.c>
    DOSHashTableSize    3097
    DOSPageCount        5
    DOSSiteCount        50
    DOSPageInterval     2
    DOSSiteInterval     2
    DOSBlockingPeriod   10
</IfModule>


参数简单说明:
DOSHashTableSize 3097 记录和存放黑名单的哈西表大小,如果服务器访问量很大,可以加大该值
DOSPageCount 5 同一个页面在同一时间内可以被同一用户访问的次数,超过该数字就会被列为攻击,同一时间的数值可以在DosPageInterval参数中设置
DOSSiteCount 50 同一个用户在同一个网站内可以同时打开的访问数,同一个时间的数值在DOSSiteInterval中设置
DOSPageInterval 2 设置DOSPageCount中时间长度标准,默认值为1
DOSSiteInterval 2 设置DOSSiteCount中时间长度标准
DOSBlockingPeriod 10 被封时间间隔秒,这中间会收到 403 (Forbidden) 的返回


其他可选参数:
DOSEmailNotify webmaster@freeoa.net 设置受到攻击时接收攻击信息提示的邮箱地址。
DOSSystemCommand “su - someuser -c ‘/sbin/… %s …’” 受到攻击时Apache运行用户执行的系统命令
DOSLogDir “/var/lock/mod_dosevasive” 攻击日志存放目录/var/lock/mod_dosevasive


mod_security
ModSecurity is a web application firewall (WAF). With over 70% of attacks now carried out over the web application level, organisations need all the help they can get in making their systems secure. WAFs are deployed to establish an increased external security layer to detect and/or prevent attacks before they reach web applications. ModSecurity provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.


一些模块的使用总结

对于mod_limitipconn,其实该模块不仅提供客户端并发联接数的控制能力,从安全角度来说还可以起到对抗固定来源IP地址发起的 DOS攻击,包括来源固定的大量访问请求型攻击(大量GET或POST请求型的攻击),当同一来源IP地址的联接数超过限定的值后,会弹回对方的访问请求,给对方一个“503服务临时无效”的响应。当Apache服务器受到大量的访问请求型攻击的时候,由于大量的Apache进程及PHP和MYSQL运行消耗,会导致服务器资源迅速耗尽,网站打开缓慢或瘫痪。如果是此种类型的攻击,使用mod_limitipconn模块则可以有效地提升服务器的抗攻击能力,因为大量的请求被弹回,节省了服务器运行PHP及MYSQL的性能消耗。当然只要请求进了80端口,不管是接受还是弹回请求,Aapche都有运行成本,所以此方法只能是减轻而无法解决,毕竟应用层的处理效率是比较低的。

对于网站访问量比较大、使用了mod_limitipconn模块且限制同一客户端并发联接数低于3的情况下,如果用Apache默认的配置参数,极 可能经常出现“服务临时无效”的提示。因为Apache默认是设置“KeepAlive on”,且“KeepAliveTimeout 180”,所以一旦建立联接,那么在3分钟内这个联接是不会被释放的。所以如果网站不同页面点击频率比较高或图片资源比较多的话,会经常出现服务临时无效的提示。那么有两种方式去解决,一是加大并发联接数的量,比如设置为普通站点10个并发联接数,图片站点则20个。另一种方式就是如果你不想加大这个值的话,可以设置KeepAlive为off,然后缩短Timeout时间,这样联接会很快被释放出来。具体情况根据需要去调整测试,以得到一个最适合自己站 点情况的值。

如果要同时限制并发联接数与带宽的话,就用bw_mod+mod_limitipconn,因为虽然bw_mod也可以控制并发联接数,但他是针对某个目录或整个网站的并发联接数,是用来控制服务器端的总联接数,比如设置MaxConnection all 1000,那么这个网站所能接受的最大并发联接数为1000,而并不是限制每一客户端的并发联接数,而mod_limitipconn则是针对同一来源 IP的客户端的并发联接数,所以这两者的联接数限制是有所区别的。

个人感觉用了bw_mod及mod_limitipconn模块后,网站访问速度有所下降,能凭直观地感觉出来,并且CPU的负载有所上升。特别是在网站访问量比较大的情况下,这两个模块会消耗一定的主机性能,所以轻重权衡这个得大家自己根据情况来采用了。另外bw_mod里有个参数是用来设置控制精度与频率的,默认是1000毫秒,如果你想提高带宽控制精度就改小这个数值,但会消耗更多的CPU资源,反之亦然,降低精度可提升性能。

该文章最后由 阿炯 于 2017-04-28 14:28:48 更新,目前是第 3 版。