How to Configure Apache to Serve Static Files Efficiently?
Configuring the Apache HTTP Server to deliver static assets like
images, CSS, and JavaScript with optimal performance involves a
combination of caching, compression, and resource optimization. By
default, Apache is highly compatible but not fully optimized for speed.
Implementing strategies such as enabling the mod_expires
module for browser caching, using mod_deflate for Gzip
compression, and fine-tuning TCP settings can drastically reduce server
load and improve website loading times for your users.
1. Leverage Browser Caching with mod_expires
Browser caching tells visitors’ browsers to store static files
locally, reducing the number of requests sent to your server on
subsequent visits. To implement this, you need to ensure
mod_expires is enabled and configure your
.htaccess or virtual host file.
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
</IfModule>2. Enable Gzip Compression with mod_deflate
Compressing text-based assets before sending them over the network
significantly reduces file sizes, speeding up delivery. The
mod_deflate module handles this seamlessly.
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>3. Disable .htaccess Files for Better Performance
When AllowOverride All is active, Apache searches every
directory in the file path for a .htaccess file on every
single request, causing significant filesystem overhead. For production
environments, move your configurations directly into the main virtual
host file and disable .htaccess.
<Directory "/var/www/html">
AllowOverride None
Require all granted
</Directory>4. Optimize KeepAlive Settings
The KeepAlive directive allows the same TCP connection
to send multiple files, which is critical for static assets. However,
keeping connections open too long can drain server memory.
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2Setting KeepAliveTimeout to a low number (like 2 to 5
seconds) ensures that the connection remains open long enough to
download the static assets for a single page view, but closes quickly
enough to free up resources for other users.
5. Utilize KeepAlive and Event MPM
Apache offers different Multi-Processing Modules (MPMs) to handle
requests. The older prefork module assigns one process per
connection, which scales poorly for static file delivery. Switching to
the event MPM allows Apache to handle thousands of
concurrent static file requests using a dedicated pool of threads,
vastly increasing efficiency.