Rewrite rule for cache busting URLs

Igor Sysoev igor at sysoev.ru
Wed Jun 9 19:28:34 MSD 2010


On Wed, Jun 09, 2010 at 11:21:47AM -0400, bkirkbri wrote:

> Our application uses versioned URLs like http://domain.com/r123456789/resource/uri to allow for aggressive caching and easy cache invalidation.
> 
> To get this working in nginx, I currently have a config like this:
> 
> [code]
> #################################################
> set $cache_control '';
> 
> location ~ ^/r\d+/ {
>     set $cache_control 'public, max-age=2592000'; # 30 days
>     rewrite ^/r\d+(/.*)$ $1 last;
> }
> 
> location /some/resources {
>     if ( $cache_control ) {
>         add_header Cache-Control $cache_control;
>     }
>     alias /path/to/resources;
> }
> 
> location /some/other/resource {
>     if ( $cache_control ) {
>         add_header Cache-Control $cache_control;
>     }
>     alias /some/other/path;
> }
> #################################################
> [/code]
> 
> Is this a bad idea?  Likely to fail in the future?  Anyone know a better way?
> 
> Could the HTTP Headers module be improved to allow "expires" or "add_header" to be used inside an "if" condition?

Yes, there is a better way:

 location ~ ^/r\d+(/some/resources/.+)$ {
     alias /path/to/resources/$1;
     add_header Cache-Control 'public, max-age=2592000'; # 30 days
 }

 location ~ ^/r\d+(/some/other/resources/.+)$ {
     alias /some/other/resources/$1;
     add_header Cache-Control 'public, max-age=2592000'; # 30 days
 }


-- 
Igor Sysoev
http://sysoev.ru/en/



More information about the nginx mailing list