简体   繁体   中英

How to create a regex in nginx to break the browser cache?

I'm a programmer so not sure if I'm dreaming if I think I can do this kind of logic in what should be a configuration file. Simply what I need, is an nginx response such that requests which include a /cacheXXX should strip out that part of the url.

So:

/cache123/editor/editor.js -> /editor/editor.js

/cache456/admin/editor.css -> /admin/editor.css

/cache987/editor/editor.js -> /editor/editor.js

And so anything else should be ignored ie:

/hello/editor/editor.js -> /hello/editor/editor.js

The key point here is that if the url matches:

/cache XXX

Then to strip that part out and return the rest.

What would an nginx location entry look like to achieve this look like?

For context as to the point of this, I am trying to break the browser cache by supplying new urls for updated resources by changing the path to the resource, rather then changing url parameters which isn't guaranteed.

One solution is to use a regular expression location to both select the URIs that begin with /cache and extract the filename part for returning the correct file.

For example (assuming that the root is defined somewhere):

location ~ ^/cache[0-9]+(/.*) {
    try_files $1 =404;
}

The regular expression location is evaluated in order, so its relative position in the configuration file is significant. See this document for details.


You could also use a rewrite rule, for example:

rewrite ^/cache[0-9]+(/.*) $1 last;

See this document for details.


For maximum efficiency, wrap either technique within a prefix location , for example:

location ^~ /cache {
    rewrite ^/cache[0-9]+(/.*) $1 break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM