8

Is it possible to somehow customize embedded tomcat with RewriteValve? As I can see in api there are currently only methods for addContextValves and addEngineValves but as pointed tomcat in documentation, RewriteValve should be placed in Host or in a webapp's context.xml. I don't understand if addContextValves could work for this.

Thanks

Community
  • 1
  • 1
bilak
  • 4,526
  • 3
  • 35
  • 75

1 Answers1

5

Yes, it is possible. These are two steps you need to follow:

  1. Implement your own TomcatEmbeddedServletContainerFactory bean and set up the RewriteValve

      import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;  
      ...
      import org.apache.catalina.valves.rewrite.RewriteValve; 
      ... 
    
      @Bean TomcatEmbeddedServletContainerFactory servletContainerFactory() {
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
        factory.setPort(8080);
        factory.addContextValves(new RewriteValve());
        return factory;
      }
    
  2. Add a rewrite.conf file to the WEB-INF directory of your application and specify the rewrite rules. Here is an example rewrite.conf content, which I'm using in the angular application to take advantage of the angular's PathLocationStrategy (basicly I redirect everything to the index.html as we just use spring boot to serve the static web content):

      RewriteCond %{REQUEST_URI} !^.*\.(bmp|css|gif|htc|html?|ico|jpe?g|js|pdf|png|swf|txt|xml|svg|eot|woff|woff2|ttf|map)$
      RewriteRule ^(.*)$ /index.html [L]
    
  • Where do we have to put `TomcatEmbeddedServletContainerFactory` beside of `main` perhaps? – MJBZA Jul 31 '20 at 08:25