How to Configure Apache Cache in Ubuntu

Enabling Apache cache allows you to speed up your website and improve server performance. Server-based caching also allows Apache server to use less memory as well as CPU processing to serve HTTP/HTTPS requests. If you also enable browser-based caching, then it will even reduce the number of requests sent to Apache server, thereby reducing network bandwidth and data costs. So it is highly recommended to enable Apache cache if your website runs on Apache server. In this article, we will learn how to configure Apache cache in Ubuntu. These steps can be used for Apache server on most platforms.

Types of Apache HTTP Caching

Apache server provides several types of caching. In this article, we will cover two most common HTTP caching mechanisms – server side caching and browser side caching.

Server-Side Caching

This is the most common caching mechanism employed by web administrators. In this case, every piece of content belongs to one of the following 3 states.
a. Fresh – New content that is served directly from cache and is the latest.
b. Stale – Content which has expired and needs to be checked for fresh copy.
c. Non-Existent – Content does not exist in cache.

In this case, when Apache server receives a request, it will check to see if the TTL (time to live) value of the content has expired or not. If it has expired, then Apache will check to see if an updated copy is available. If an updated copy is available, then it is stored in the cache with new TTL value. On the other hand, if the fetched content has not been updated and is the latest, then it will be served as a response.

Browser-Side Caching

In this case, Apache server sets the response header Expires and max-age so that the client browser starts storing the response in browser’s local cache. Thereafter, whenever the web browser receives a request, it will automatically first check if its response is locally stored in the browser cache. If so, it will serve the cached response from the browser itself, without even sending the request to server. If the cached data is expired or outdated, then only it will send the request to web server.

How to Configure Apache Cache in Ubuntu

Here are the steps to configure Apache cache in Ubuntu.

1. Server-Side Caching

We need to use mod_cache, mod_cache_disk, mod_expires and mod_headers Apache modules for server side caching. So first, we will need to enable them using the a2enmod command.

sudo apt-get update
sudo apt-get install apache2-utils #optional - provides htcacheclean utility
sudo a2enmod cache
sudo a2enmod cache_disk
sudo a2enmod expires
sudo a2enmod headers

On some systems such as RHEL/Fedora, these modules may be enabled by default.

Next, edit your site’s virtual host configuration file such as /etc/apache2/sites/sites-available/example.com.conf. Add the following cache directives in <VirtualHost> tag.

<VirtualHost *:80>
ServerName example.com
...

CacheQuickHandler off
CacheLock on
CacheLockPath /tmp/mod_cache-lock
CacheLockMaxAge 5

<Location />
CacheEnable disk
CacheHeader on
CacheDefaultExpire 600
CacheMaxExpire 86400
ExpiresActive on
ExpiresDefault "access plus 5 minutes"
Header merge Cache-Control public
</Location>

<VirtualHost/>

Save and close the file. Let us look at the above code in detail

  1. CacheQuickHandler off – Will serve cached content only after authentication. This is secure and prevents unauthorized users from accessing your content, such as in data reporting systems.
  2. CacheEnable disk – Setup disk caching for location /
  3. CacheRoot – Specifies location to store cache files
  4. ExpiresActive and ExpiresDefault – Set expiration headers for content

Check syntax using apachectl utility. Restart Apache server to apply changes.

sudo apachectl configtest
sudo service apache2 restart

You can use htcacheclean utility once in a while to clean up disk cache. Here is a sample command that can be setup as a cron job to run automatically.

sudo htcacheclean -d30 -t -p /var/cache/apache2/mod_cache_disk -l 10M

2. Browser-Side Caching

In this method, Apache uses the cache of client web browser to store static files. This reduces the number of requests sent to Apache server.

For this solution, we only need mod_expires and mod_headers modules. So we enable them first.

sudo a2enmod expires
sudo a2enmod headers

Next, add the following lines to .htaccess file in your site’s root directory or your site’s virtual host configuration file.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 day"

ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"

</IfModule>

In the above code, we first check if mod_expires is enabled or not. If so, then we set the expiration for different types of files to different durations, using ExpiresByType directive.

Save and close the file. Restart Apache server to apply changes.

sudo service apache2 restart

Benefits of Caching

  1. Better Performance – When response data is cached, then in most cases, it is served from the cache itself, instead of the server processing the request. This allows applications and websites to deliver better response times. Consequently, it creates a smooth user experience.
  2. Reduced Server Load – Since many server requests are directly processed by cache and not sent to backend server, this reduces the server load. In fact, for the same reason, it also reduces database load. This prevents performance bottlenecks and allows your site to handle more users.
  3. Cost Saving – Since fewer number of requests are sent to backend server and database, but served from server cache itself, you don’t require expensive, high end infrastructure to run your website. Similarly, if you enable browser caching, then the client web browser will serve static content from browser’s cache instead of sending request to server. This will save network bandwidth resulting in data cost saving.
  4. Scalable – Since you do not need high end infrastructure to run your website, you can easily scale it to handle high traffic. It also makes your website more resilient to handle sudden spike in traffic. It allows your site to give good performance during peak traffic.
  5. Better User Experience – Since your website works faster, with lower server load, it improves user experience significantly.

Additional Info

Apache further provides two additional types of caching, which are used for very specific use cases.

  1. File Caching – In this case, Apache server will open the file descriptors of cached files and keep them available to respond quickly.
  2. Key-Value caching – In this approach, Apache server will cache a shared object of key-value pairs. This is used for quick lookups such as during SSL authentication, where computing these values is time consuming.

However, in most cases, HTTP caching is sufficient.

Conclusion

In this article, we have learnt how Apache caching works. We have learnt how both server side caching as well as browser side caching work. We have also learnt how to enable Apache cache for each of these cases. Depending on your requirement, you can use any of these solutions.

Also read:
How to Increase File Upload Size in Apache
How to Disable Cache in Apache
How to Restrict Access By IP in Apache

Leave a Reply

Your email address will not be published. Required fields are marked *