Tomcat: Cache-Control

Since Tomcat 7 there is a container provided expires filter that may help. See:

  • Tomcat 10: https://tomcat.apache.org/tomcat-10.0-doc/config/filter.html#Expires_Filter
  • Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/filter.html#Expires_Filter
  • Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/filter.html#Expires_Filter
  • Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Expires_Filter
  • Tomcat 6 (unofficial backport): https://github.com/bnegrao/ExpiresFilter

ExpiresFilter is a Java Servlet API port of Apache mod_expires. This filter controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

<filter>
    <filter-name>ExpiresFilter</filter-name>
    <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
    <init-param>
        <param-name>ExpiresByType image</param-name>
        <param-value>access plus 10 days</param-value>
    </init-param>
    <init-param>
        <param-name>ExpiresByType text/css</param-name>
        <param-value>access plus 10 hours</param-value>
    </init-param>
    <init-param>
        <param-name>ExpiresByType application/javascript</param-name>
        <param-value>access plus 10 minutes</param-value>
    </init-param>
    <!-- Let everything else expire immediately -->
    <init-param>
        <param-name>ExpiresDefault</param-name>
        <param-value>access plus 0 seconds</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>ExpiresFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

Leave a Comment