Tomcat 8 URL Rewrite

时光毁灭记忆、已成空白 提交于 2019-11-27 17:42:16

问题


I have an AngularJS webapp and Jersey backend. I need to setup URL rewriting, so everything except given exceptions will be rewritten to Angular's index.html.

Eg.:

http://my.domain.com/about will be rewritten
http://my.domain.com/photos/photo1.jpg will NOT be rewritten (file photo 1 exists)
http://my.domain.com/rest/myservice will be NOT be rewritten (it is a call to REST service)

I have set up the Tomcat 8 URL Rewrite Valve as follows:

in conf/server.xml

<Host name="my.domain.com" appBase="webapps/MyDomainServer" unpackWARs="true"
           autoDeploy="true"
           xmlValidation="false" xmlNamespaceAware="false">
  <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
  <!-- access logging, aliases,...-->
</Host>

in conf/Catalina/my.domain.com/rewrite.config

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} ^/rest.*
RewriteRule ^ - [L]

RewriteRule ^ index.html [L]

Tomcat ignores my rewrite settings, nothing is rewritten, no error/exception is in the log. What am I doing wrong? Thanks in advance.

I have tried to move RewriteValve to config.xml in META-INF and rewrite config to WEB-INF, but it behaved in the same way.


回答1:


I have found the solution, problem was in wrong/faulty rewrite.config file. Correct should be:

RewriteCond %{REQUEST_URI} ^/(css|img|js|partials|rest|favicon).*$
RewriteRule ^.*$ - [L]

RewriteRule ^.*$ /index.html [L,QSA]

On the first line are enumerated URIs which should not be rewritten. Everything else will be rewritten to index.html.




回答2:


Is this deployed as a java web app (WAR)? You could implement this in your web.xml:

<servlet>
   <servlet-name>index</servlet-name>
   <jsp-file>/index.html</jsp-file>
</servlet>

<servlet-mapping>
   <servlet-name>index</servlet-name>
   <url-pattern>/</url-pattern>
   <url-pattern>/about</url-pattern>
   .. as many as you need ..
<servlet-mapping>



回答3:


I couldn't get this to work with the REQUEST_URI, and I didn't like having to whitelist specific files anyway, so I solved it in a slightly different manner.



来源:https://stackoverflow.com/questions/28767585/tomcat-8-url-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!