Question

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

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;
}

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Hello,

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:

https://www.digitalocean.com/community/tutorials/how-to-implement-browser-caching-with-nginx-s-header-module-on-ubuntu-16-04

Let me know how it goes! Regards, Bobby