Tomcat 8 URL Rewrite Issues

后端 未结 2 765
Happy的楠姐
Happy的楠姐 2020-12-10 05:56

I have got the tomcat 8 rewrite to work but seems to missing something in rewrite.config that is causing the last condition to not execute. For benefit of others, i have the

相关标签:
2条回答
  • 2020-12-10 06:28

    I seem to have got it fixed. There are couple of things i found and sharing it for others. The below thing worked finally for me. Below are the contents in rewrite.config. It should be placed in webapps//WEB-INF/ directory.

    RewriteCond %{REQUEST_URI} .*\.(css|js|html|png|jpg|jpeg|gif|txt|ttf|json|woff|ico)$ [OR]
    RewriteCond %{REQUEST_URI} ^(/api/).*$ [OR]
    RewriteRule ^(.*)$ - [L]
    
    RewriteRule ^(.*)$ /index.html 
    

    There are a couple of things that were needed. The way i ensure my app is the default app is by adding below snippet in HOST configuration in server.xml. Please note that if you are using this approach to make your app the default app the valve adding should be done in the Context block in server.xml and it works and putting the same in your application/META-INF/context.xml does not seem to do the trick. It surely loads the configuration but rewrite does not happen. The PreResources thing kept in the application/META-INF/context.xml seems to work fine.

    server.xml snippet

    <Host name="localhost"  appBase="webapps"
                unpackWARs="false" autoDeploy="false" deployOnStartup="false">
    
            <Context path="" docBase="myapp" reloadable="false">
                <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" asyncSupported="true"/>
            </Context>  
            ....
    </Host>
    

    HTH, Thanks

    0 讨论(0)
  • 2020-12-10 06:36

    I found this question because I had a similar problem. I spent hours looking for a solution that didn't require me to whitelist specific file types. Eventually I decompiled org.apache.catalina.valves.rewrite.RewriteValve and found the answer.

    My case is similar, but my Angular app is nested inside an older non-Angular app. That means that the URL to it someting like http://localhost:8080/mywebapp/ng/index.html (the app's base-href is thus "/mywebapp/ng").

    I had no luck with rules using REQUEST_URI, REQUEST_FILENAME, or SCRIPT_FILENAME. What worked for me was SERVLET_PATH (no idea why).

    I wound up with a solution including these two files:

    /META-INF/context.xml:

    <?xml version='1.0' encoding='utf-8'?>
    <Context>
        <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
    </Context>
    

    /WEB-INF/rewrite.config:

    RewriteCond %{SERVLET_PATH} !-f
    RewriteRule ^/ng/(.*)$ /ng/index.html [L]
    

    The result is that everything which is not a real file gets served by the Angular app.

    Note: This worked on Tomcat 8.0 with an AoT compiled Angular2 (v4.0.0) app nested in an existing web-application.

    0 讨论(0)
提交回复
热议问题