Report this

What is the reason for this report?

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

Posted on August 22, 2019

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


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!

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.

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.