Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I heard recently that Nginx has added caching to its reverse proxy feature. I looked around but couldn't find much info about it.

I want to set up Nginx as a caching reverse proxy in front of Apache/Django: to have Nginx proxy requests for some (but not all) dynamic pages to Apache, then cache the generated pages and serve subsequent requests for those pages from cache.

Ideally I'd want to invalidate cache in 2 ways:

  1. Set an expiration date on the cached item
  2. To explicitly invalidate the cached item. E.g. if my Django backend has updated certain data, I'd want to tell Nginx to invalidate the cache of the affected pages

Is it possible to set Nginx to do that? How?

share|improve this question

12 Answers 12

up vote 73 down vote accepted

I don't think that there is a way to explicitly invalidate cached items, but here is an example of how to do the rest. Update: As mentioned by Piotr in another answer, there is a cache purge module that you can use. You can also force a refresh of a cached item using nginx's proxy_cache_bypass - see Cherian's answer for more information.

In this configuration, items that aren't cached will be retrieved from example.net and stored. The cached versions will be served up to future clients until they are no longer valid (60 minutes).

Your Cache-Control and Expires HTTP headers will be honored, so if you want to explicitly set an expiration date, you can do that by setting the correct headers in whatever you are proxying to.

There are lots of parameters that you can tune - see the nginx Proxy module documentation for more information about all of this including details on the meaning of the different settings/parameters: http://nginx.org/r/proxy_cache_path

http {
  proxy_cache_path  /var/www/cache levels=1:2 keys_zone=my-cache:8m max_size=1000m inactive=600m;
  proxy_temp_path /var/www/cache/tmp; 


  server {
    location / {
      proxy_pass http://example.net;
      proxy_cache my-cache;
      proxy_cache_valid  200 302  60m;
      proxy_cache_valid  404      1m;
    }
  }
}
share|improve this answer
6  
This is a reasonable first step for new apps that don't have 20k/req/s. –  Barry May 2 '11 at 13:05
4  
@Barry what shall be the second steP? –  Pineapple Under the Sea May 31 '12 at 0:52
24  
@Legit - I don't know, but traditionally the last step is "Profit" :-) –  Stephen C Jul 17 '12 at 7:30

I suggest you give Varnish a try. Varnish is specifically designed as a reverse proxy cache. It will honor all cache control headers you send from the origin server, which satisfies your first request.

For your second request, explicit invalidation. My strong recommendation is to change the name of the url of the resource you want to invalidate, either by renaming the file or using some form of query string cache buster. Varnish does have a PURGE operation that will remove the resource from Varnish's cache, but it will not give you control over any other caches between you and the user. As you've said you want to explicitly purge a resource, then standard http control headers won't help you. In that cases the most foolproof way to defeat the caching of a resource is to rename it.

share|improve this answer
    
Could you explain what did you mean by "renaming the file or using some form of query string cache buster"? I'm not sure I understand why it's not a good idea to use an operation like PURGE. –  Continuation Jun 24 '09 at 15:54
5  
+1 for varnish. It's always much better to use the right tools for the job. –  Tom O'Connor Nov 17 '09 at 11:53
4  
@below: There's almost no hope of touching varnish in the arenas of performance and versatility. This is backed by one of the lead FreeBSD kernel developers and a dedicated team based in Europe. Varnish is in production at twitter, heroku and many more. –  Barry May 2 '11 at 12:59
2  
The simplest example of a cache-buster is to append a version number in a query string to a static resource, so style.css becomes style.css?123. When you want to push a new version of the file you change the url of the resource to style.css?124 and now the caches will pick it up as an entirely new asset to be cached separately. Apache will serve the file style.css with any query string appended, so no changes to the actual file are required. –  chmac Apr 20 '12 at 12:27
3  
If possible, it's best to put the cache buster into the filename itself, such as style.v123.css because some caches will not cache requests that have a query string. –  Noah McIlraith Jul 29 '12 at 15:34

You can specifically invalidate cached pages through

proxy_cache_bypass       

Say you want to cache a page, set cache this way

location = /pageid {
  proxy_pass http://localhost:82;
  proxy_set_header   Host             $host;
  proxy_set_header   X-Real-IP        $remote_addr;
  proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
  proxy_ignore_headers Set-Cookie; 
  proxy_ignore_headers Cache-Control; 
  proxy_cache_bypass        $http_secret_header;
  add_header X-Cache-Status $upstream_cache_status;
}

Now, when you want to invalidate that page and cache again

Do a secret curl call with the header

curl "www.site.com/pageid" -s -I -H "secret_header:true" 

It will invalidate and cache it.

Works from nginx 0.7.

As an added bonus the add_header X-Cache-Status can be used to check if the page is from cache or not.

share|improve this answer

For invalidating selected pages you can use "cache_purge" patch for nginx-0.8.x which does exacly what you want ;)

It's available here.

share|improve this answer

Caching is pretty new function in nginx (and not so well documented for now), but stable enough to be used in production.

share|improve this answer

I believe NginxHttpProxyModule is capable of caheing http requests. Look for the directives starting with:

proxy_cache

Yes, it is possible to control cache behaviour via directives like:

proxy_cache_valid
share|improve this answer

Most caching tools (Citrix) allow a force-refresh (Ctrl+r) to repopulate a cached page.

Here's a trick I found to do something similar in nginx.

server  {
        # Other settings
        proxy_pass_header       Set-Cookie; # I want to cache logged-in users
        proxy_ignore_headers    X-Accel-Redirect;
        proxy_ignore_headers    X-Accel-Expires Expires Cache-Control;
        if ($http_cache_control ~ "max-age=0") {set $eac 1;}
        proxy_cache_bypass $eac;
}

This assumes that when you do a Ctrl+r in your browser, the Cache-Control header has max-age=0 in its request. I know Chrome does this, but I have not tried in other browsers. Adding more header fields can be easy, by just adding more if statements that set the $eac variable to 1.

share|improve this answer

Based on the fact that you can't find docs on it, I'd be a little bit wary about relying on it in production. Have you considered Varnish? It's my "nginx of reverse proxies", small, lightweight, doing one job and doing it well.

share|improve this answer
    
THe documentation is here: wiki.nginx.org/NginxHttpProxyModule#proxy_cache –  rmalayter Sep 9 '10 at 4:00

If you use eTags on your application and put nginx in front of it then it will take care of the expiration for you, because if the eTag changes it will invalidate the cache.

share|improve this answer
    
Really? It seeems like ngnix matches the etag and never talks to the application to find out if there is an updated etag. –  John Naegle Jun 26 '13 at 18:55
fastcgi_cache_path  /opt/nginx-cache  levels=2:2   keys_zone=img:50m;

    location /img/ {
        fastcgi_pass $backend;
        include fcgi_params;
        fastcgi_intercept_errors off;   
        fastcgi_cache_key $server_addr$request_uri;       
        fastcgi_cache img;
        fastcgi_cache_valid any 1m;
        fastcgi_hide_header Set-Cookie;
    }

This creates cache for /img/ location. It is in /opt/nginx-cache. Objects are cached for 1 minute.

You can write different response codes instead of any.

Now you can't invalidate cache for selected pages. Maybe in 0.8.x it will be possible.

share|improve this answer
    
The original question was about using nginx in front of Apache, not in front of fastcgi application handled by nginx. –  Graham Dumpleton Jul 13 '09 at 1:52

There is an nginx plugin called ncache which claims to be "a web cache system base on nginx web server. faster and more efficient than squid. "

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.