How to Adjust KeepAliveTimeout in Apache?

This article provides a step-by-step guide on how to configure the KeepAliveTimeout directive in the Apache HTTP Server. You will learn what this setting does, why it is important for server performance, where to locate the configuration files on different operating systems, and how to safely apply your changes. By optimizing this value, you can strike the right balance between server resource consumption and a fast user experience.

Understanding KeepAliveTimeout

The KeepAliveTimeout directive defines the number of seconds Apache will wait for a subsequent request on a persistent connection before closing it. When a browser connects to your server, it often needs to download multiple files like HTML, CSS, JavaScript, and images. Enabling KeepAlive allows these files to be sent over a single connection rather than opening a new one for every file.

Step-by-Step Configuration

To modify this setting, you need administrative (root) access to your server via SSH.

1. Locate the Configuration File

Depending on your operating system, the main Apache configuration file or the specific KeepAlive configuration file will be in different locations:

2. Edit the File

Open the configuration file using a text editor like nano or vi. For example, on Ubuntu, run:

sudo nano /etc/apache2/apache2.conf

3. Modify the Directives

Scroll through the file to find the KeepAlive settings. If they do not exist, you can add them to the bottom of the file. Ensure KeepAlive is turned on, and then adjust the timeout value:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 3

In this example, Apache is configured to wait 3 seconds for a new request before dropping the connection.

4. Test the Configuration

Before restarting Apache, always test your configuration file for syntax errors to avoid bringing down your website.

If the terminal outputs Syntax OK, you are safe to proceed.

5. Restart Apache

Apply the changes by restarting the Apache service:

sudo systemctl restart apache2
sudo systemctl restart httpd

Verifying the Changes

You can verify that your settings are working by monitoring your server traffic or using developer tools in your web browser. Inspect the network tab while loading your website; the Connection: keep-alive header should be visible in the response headers, and idle persistent connections should close automatically according to your newly defined limit.