Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm implementing a sort of url-shortener service. What happens is that I have some backend app server that takes in a request, does some computation and returns a 301 redirected url back upstream to an nginx frontend:

request --->   nginx  ---->  app_server

What I want to be able to do is cache this returned 301 url for the same request (a specific url with a "short code").

Does nginx do this caching automatically? Or should I drop in something like varnish in between nginx and the app_server? I can easily cache this in memcache, but that would require hitting the app_server, which I'm sure can be dispensed with after the first request.


share|improve this question

You can configure Nginx to do that.

Example: to cache a redirect (301 or 302) up to 60 minutes:

proxy_cache_valid 301 302 60m;
share|improve this answer
301 is a permanent redirect, so it can be cached for much longer periods (e.g. 1y). The application overrides this with its Expires or Cache-Control headers. – Michael Hampton Aug 29 '12 at 9:23

I am also researching this and from what I understand Varnish does redirects very indirectly. And the same for proxy caching in Nginx. So from what I understand we need Varnish for caching and upstreams and Nginx only for redirects?

This is probably not specific for your application though.

share|improve this answer

Varnish caches any HTTP responses that match its logic, and redirects are simply HTTP 301 or 302 responses that can be cached easily. Of course, you can override the default logic via Varnish's VCL language.

Our Varnish server caches redirects automatically. You control the cache TTL by setting a 'Cache-Control: max-age' (or Expires) header in your backend response. If you don't specify a TTL, I believe the default is 120s. Make sure you don't set any cookies on the domain, or discard them when they enter Varnish, or requests will fall through Varnish. We simple created a separate subdomain for redirects, and explicitly discard any incoming and outgoing cookies via VCL.

As a side note for other use-cases: You can offload redirects to Varnish entirely, so they never hit the backend. Some example code:

share|improve this answer

Your Answer


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.