Search code examples
springapachespring-bootthymeleafreverse-proxy

Setting context name in thymeleaf with spring boot deployed on tomcat8 behind apache reverse proxy


I am trying to :

  • setup a sub domain, in which root path / will proxy local tomcat's running thymeleaf + spring boot app at http://localhost:8080/myuiapp/,

  • With a flexibility that I can change the context path to /application or /demo or /anything in future (with just apache config changes) without any codebase or tomcat config changes.

The problem I'm facing is:- thymeleaf is not changing context name when deployed on standalone tomcat8. (I got to know that context path property affect only in embedded tomcat server)

So th:href="@{/assets/vendors/global/vendors.bundle.css}" is computed as href=/myuiapp/assets/vendors/global/vendors.bundle.css always.

Here's one of the virtual host config that I've tried:

<VirtualHost _default_:443>
        ServerName foo.domain.com
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/foo.domain.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/foo.domain.com/privkey.pem

        ProxyPreserveHost On

        ProxyPass / http://localhost:8080/myuiapp/
        ProxyPassReverse / http://localhost:8080/myuiapp/

        ProxyPass /newapp/ http://localhost:8080/myuiapp/
        ProxyPassReverse /newapp/ http://localhost:8080/myuiapp/
</VirtualHost>

I have tried the following things:

1) Apache sending headers to application and application respecting those headers

SSLProxyEngine on
ProxyPreserveHost on
RequestHeader set X-Forwarded-Proto https
RequestHeader set X-Forwarded-Port 443

server.use-forward-headers=true

2) Setting context path manually

System.setProperty("server.servlet.context-path", contextPath)

3) Server-relative URLs in Thymeleaf - link (It solves my first problem of Root / context path but not /any context path)

<a th:href="@{~/billing-app/showDetails.htm}">

Need your help in setting dynamic context-name, when we deploy on standalone tomcat which is recognised by thymeleaf as well.


Solution

  • I had a similar issue. I had the following line in the html file

    <link rel="stylesheet" th:href="@{/css/stylesheet.css}"/> 
    

    and the stylesheet was found at http://localhost:8321/css/disclaimer.css and correctly applied (notice the lack of application name on the path). However on production the new link to the css was https://example.com/app-name/css/stylesheet.css but in the html it was still pointing wrongly to https://example.com/css/stylesheet.css

    To fix this I had to remove the initial / from href like so:

     <link rel="stylesheet" th:href="@{css/stylesheet.css}"/> 
    

    and the css applied both locally and in production.