简体   繁体   English

如何在 nginx 中创建正则表达式来破坏浏览器缓存?

[英]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.我需要的只是一个 nginx 响应,这样包含 /cacheXXX 的请求应该去掉 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:这里的关键是,如果 url 匹配:

/cache XXX /缓存XXX

Then to strip that part out and return the rest.然后剥离该部分并返回 rest。

What would an nginx location entry look like to achieve this look like? nginx 位置条目会是什么样子来实现这个外观?

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.关于这一点的上下文,我试图通过更改资源的路径来为更新的资源提供新的 url,而不是更改不能保证的 url 参数来打破浏览器缓存。

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.一种解决方案是对 select 以/cache开头的 URI 使用正则表达式位置,并提取文件名部分以返回正确的文件。

For example (assuming that the root is defined somewhere):例如(假设root在某处定义):

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.正则表达式location是按顺序求值的,所以它在配置文件中的相对 position 很重要。 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中,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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