Add Cache-Control-Header / Expire-Header in NGINX

Posted August 22, 2019 64.3k views
NginxCachingUbuntu 18.04

Hi, I added both cache-control-header and expire-header to /etc/nginx/sites-enabled/* on the console (there was no server block in the main conf file). Still, both Pagespeed and GTMetrix say that browser caching is not leveraged. It is making my site considerably slower, please help!

These are the codes I used:

location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$ {
 expires 30d;
 add_header Cache-Control "public, no-transform";

location ~* .(jpg|jpeg|gif|png|svg)$ {
expires 365d;

location ~*  \.(pdf|css|html|js|swf)$ {
    expires 2d;

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer


I would recommend first testing this manually with curl rather than using an online tool as sometimes they tend to be unreliable:

curl -I http://yourdomain/test.jpg

You should see something like this:

HTTP/1.1 200 OK
Server: nginx/1.10.0 (Ubuntu)
Date: Sat, 10 Sep 2016 13:50:41 GMT
Content-Type: image/jpeg
Content-Length: 1024
Last-Modified: Sat, 10 Sep 2016 13:11:36 GMT
Connection: keep-alive
ETag: "57d40688-400"
<^>Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000<^>
Accept-Ranges: bytes

If you do not see the headers, I would recommend following the steps here from this step by step guide:

Let me know how it goes!

by Mateusz Papiernik
In this tutorial, we will look at how to use Nginx's header module to implement browser caching.