How to Limit Connections in Apache


limit connections in apache

By Default, Apache supports up to 256 concurrent connections. If you are running a high traffic website, then it might result in high bandwidth consumption. Here’s how you can limit connections in Apache to ensure that

 

How to Limit Connections in Apache

Here are the steps to limit connections in Apache (or any other server). Please note, it is not really easy to limit connections in Apache. So we use iptables firewall in Linux to limit the number of connections to a specific port (e.g port 80).

Before we proceed, please ensure iptables is installed on your system. It should be available on most linux systems. You can check it with the command


$ man iptables

If you see the manual, it means iptables is installed. If you don’t then here’s how to install it on CentOS/RHEL/Fedora and Ubuntu/Debian systems

 

Here’s the syntax of iptables


$ /sbin/iptables -A INPUT -p tcp --syn --dport $port -m connlimit --connlimit-above N -j REJECT --reject-with tcp-reset
$ service iptables save

 

Limit connections from IP

If you want to limit up to 15 connections from one ip to port 80 (HTTP)

$ iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 15 --connlimit-mask 32 -j REJECT --reject-with tcp-reset

 

If you want to limit up to 15 connections from one ip to port 22 (SSH)

$ iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 15 --connlimit-mask 32 -j REJECT --reject-with tcp-reset

 

Limit Connections per Second

If you want to limit connections per second, instead of no. of connections per IP

iptables -A INPUT -m state --state RELATED,ESTABLISHED -m limit --limit 150/second --limit-burst 160 -j ACCEPT

In this case, 160 connections are allowed before imposing a limit of 150 new connections/second.

 

Save iptables changes

Remember to save iptables changes. Otherwise, they won’t be applied.

$ service iptables save

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!