Spring Security 默认添加以下缓存头:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
这对我们的 HTML 页面来说是一个很好的设置。对于静态资源(图像、CSS 等),我们希望将它们缓存起来。根据Spring documentation ,它可以这样配置:
@EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/")
.setCachePeriod(31556926);
}
}
这会产生以下 HTTP header :
Cache-Control: max-age=604800
Pragma:
Expires: 0
这很好,除了 Expires
header ,它仍然指示不应缓存文档。 (标准规定 max-age
优先于 Expires
。但我们的中间缓存仍然将其视为不可缓存。)
我们如何删除可缓存文档的 Expires
header (或将其设置为空白)?为什么我们配置了缓存期,Spring 不去掉?
最佳答案
这似乎与 spring-security#3759 有关.您可以通过忽略(有点不相关)SPR-14005 中列出的特定 URL 来解决此问题.但是,不建议这样做(即使 URL 指向静态资源),因为这意味着 URL 的所有安全性都被禁用。
相反,用户应考虑使用此解决方法:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
RequestMatcher notResourcesMatcher = new NegatedRequestMatcher(new AntPathRequestMatcher("/resources/**"));
HeaderWriter notResourcesHeaderWriter = new DelegatingRequestMatcherHeaderWriter(notResourcesMatcher , new CacheControlHeadersWriter());
http
.headers()
.cacheControl().disable()
.addHeaderWriter(notResourcesHeaderWriter);
}
}
当 Spring Security 4.1 发布时 spring-security#3759将被修复,这应该不是问题。
关于java - 如何使用 Spring 缓存控件删除 Expires header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011255/