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.

Is it possible to have Nginx cache all 301 redirect requests for proxy_pass?

For example:

Request #1: Client A requests /some/path -> sent to proxy_pass -> results in 301 redirect to /some/other/path -> nginx caches this response since it's a 301 redirect.

Request #2: Client B requests /some/path -> nginx returns cached 301 redirect to /some/other/path.

share|improve this question

3 Answers 3

nginx already can cache 301 redirects. You can change the amount of time they are cached with the proxy_cache_valid directive:

proxy_cache_valid 301 365d; # Cache permanent redirects for a whole year
share|improve this answer
up vote 2 down vote accepted

I found that @Michael's answer got me most of the way there, but when I turned on proxy_cache, it would automatically cache files with Expires and Cache-Control. So I ended up with this solution.

proxy_cache_path /tmp/nginx levels=1:2 keys_zone=main-cache:8m max_size=1000m inactive=600m;
proxy_temp_path /tmp/nginx/tmp;
proxy_cache main-cache;
proxy_cache_valid 301 60m;
proxy_cache_key "$scheme://$host$request_uri";
proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
share|improve this answer
1  
That's what a cache does. Nowhere did you ever mention that you didn't want anything else cached. –  Michael Hampton Sep 9 '12 at 21:02

If you want redirect all, you could use this way:

location / {
  proxy_pass http://127.0.0.1:8080/VirtualHostBase/https/$server_name:443/some/path/VirtualHostRoot;
}

Your examples could need the combination of rewrite and proxy_pass:

location / {
  rewrite ^(.*)$ /VirtualHostBase/https/$server_name:443/some/path/VirtualHostRoot$1 break;
  proxy_pass http://127.0.0.1:8080;
}

Warning: you have got different rewrite redirect effect: break returns 301 instead permanent returns 302.

EDIT Upstream this module/s you need use proxy_cache_valid diretive:

proxy_cache_valid  301 1h;

Warning, upstream cache-related directives have priority over proxy_cache_valid value, in particular the order is:

  1. X-Accel-Expires
  2. Expires/Cache-Control
  3. proxy_cache_valid

Reference: HttpProxyModule, Nginx reverse proxy + URL rewrite

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.