Follow this Blog!

May 2, 2013

f Comment

Why is Nginx Expires Directive Not Working?

Amazon Nginx is a popular web server and I use it to host all my websites. In the server configuration file I use expires directive to control browser cache time by adding Cache-Control and Expires in the response HTTP headers. However there's a trick that may cause it not to work properly.

If you do exactly what http://wiki.nginx.org/HttpHeadersModule asks you to do you may still not see Cache-Control and Expires headers in the HTTP response of a page served by your NGINX web server. This may be due to where you place expires directive.

The following is a sample configuration.
server {
 listen  80;
 server_name  www.programmingincpp.com;
 expires 1y; #works here

 location / {
  expires 1y; #does NOT work here
  root /home/ubuntu/repository201207/trunk-cpp/;
  
  ...
 }
 ...
}
I am not sure why the location of expires directive within the location block would cause the server to not send Cache-Control header. Anyway simply move out the directive and restart Nginx server and it should work.

When the expires directive doesn't work here are the example HTTP response headers:

Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html
Date:Thu, 02 May 2013 03:32:50 GMT
Server:nginx/0.7.65
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.2-1ubuntu4.14

When the expires directive works here are the example HTTP response headers:

Cache-Control:max-age=31536000
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html
Date:Thu, 02 May 2013 03:33:38 GMT
Expires:Fri, 02 May 2014 03:33:38 GMT
Server:nginx/0.7.65
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.2-1ubuntu4.14

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael