Nginx – How to set expires headers for images

Categories: nginx

Nginx - How to set expires headers for images

In Nginx, you can easily set browser caching for your images. Nginx sets the ‘Expires’ and ‘Cache-Control’ http request headers for images nginx serves. This allows the client’s browser to cache the images for the amount of time specified by the expires tag inside the location block of code.

Here’s the location block I’m using in my Nginx virtual host configuration file:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires 1y;
        log_not_found off;
}

You can use the curl command on unix/linux/mac to see the full headers for a request. Here is an example of the full headers nginx is setting for an image after using expires headers.

# curl -I http://nicholaskuechler.com/images/2011/02/cropped-andromeda-galaxy11.jpg
HTTP/1.1 200 OK
Server: nginx/1.0.0
Date: Sun, 24 Apr 2011 04:26:46 GMT
Content-Type: image/jpeg
Content-Length: 66713
Last-Modified: Fri, 25 Feb 2011 08:34:30 GMT
Connection: keep-alive
Expires: Mon, 23 Apr 2012 04:26:46 GMT
Cache-Control: max-age=31536000
Accept-Ranges: bytes

I noticed after putting the nginx expires in place and utilizing client browser caching, my Google Page Speed score increased by 5 points. Excellent!