Nginx – How to Set ‘Expires’ and ‘Cache-Control’ Headers

nginx

I have a php website running on a DigitalOcean droplet (nginx server), and i also use Cloudflare. Recently, my website was hit by something that i yet did not understand.. as my CPU usage was usually 1-2% and it went to 100% for a few hours resulting in my server crashing.

My Cloudflare analytics showed an extremely high number of visitors – of which i am sure was not human traffic.

Cloudflare asked to see my nginx error logs and access logs. Following is their reply –

You have 2 caching headers that are going to expire your assets as
soon as they get stored at our edge.

< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0

and

< Expires:> Thu, 19 Nov 1981 08:52:00 GMT. 

Because the Expires header is set to
sometime in the past, the cache is going to be expired the moment it
hits our edge. Then you have your cache-control header basically
saying do not store any of the assets at our edge, but you have a
caching enabled, so our edge will continue to crawl your site. This
can cause what looks like a DoS attack against your origin.

Can someone please tell me how can i set my Expires header and Cache-control header on my Nginx server?

Your reply is appreciated, thanks!

Best Answer

You have an incorrect setting in your php.ini file:

The session.cache_limiter value is set to nocache in the default php.ini file and needs to be changed.

session.cache_limiter should be defined and set, either to public which inserts public cache-control headers, or to '' (blank), which doesn't insert any cache-control headers, and the headers sent by your application will then be used, if any.