Ubuntu – Apache2 enable expires headers

 

To enable expires headers or mod_expires with apache2 in Ubuntu OS use following command

$ a2enmod expires

.

Now restart apache2 with any of following command:

$ service apache2 restart

or

$ /etc/init.d/apache2 restart

There are 2 ways to add expire headers

  • FileMatch with ExpiresDefault directives
  • ExpiresByType

To enable expires headers with FileMatch with ExpiresDefault directives add following lines in /etc/apache2/sites-available/default file:

<VirtualHost *:80>
...
...
<IfModule mod_expires.c>
          <FilesMatch "\.(png|css|js|jpe?g|gif)$">
                      ExpiresActive On
                      ExpiresDefault "access plus 1 day"
          </FilesMatch>
</IfModule>
</VirtualHost>

Above code will tell browsers to cache .png, .css, .js, .jpg, .jpeg, and gif for one day.

To enable expires headers with ExpiresByType add following lines in /etc/apache2/sites-available/default file:

<VirtualHost *:80>
...
...
          ExpiresActive on

          ExpiresByType image/jpg "access plus 60 days"
          ExpiresByType image/png "access plus 60 days"
          ExpiresByType image/gif "access plus 60 days"
          ExpiresByType image/jpeg "access plus 60 days"

          ExpiresByType text/css "access plus 1 days"

          ExpiresByType image/x-icon "access plus 1 month"

          ExpiresByType text/javascript "access plus 1 week"
          ExpiresByType application/x-javascript "access plus 1 week"
          ExpiresByType application/javascript "access plus 1 week"
</VirtualHost>

After any thing in /etc/apache2/sites-available/default file you need to restart apache2 to changes make effect.

You can use following units for in expires headers:

  • years
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds

-Sany

Leave a comment