Java Tomcat 8 URL 重写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28767585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tomcat 8 URL Rewrite
提问by kamelot
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.
我有一个 AngularJS webapp 和 Jersey 后端。我需要设置 URL 重写,所以除了给定的异常之外的所有内容都将被重写为 Angular 的 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:
我已经按如下方式设置了 Tomcat 8 URL Rewrite Valve:
in conf/server.xml
在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
在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.
Tomcat 忽略我的重写设置,没有重写任何内容,日志中没有错误/异常。我究竟做错了什么?提前致谢。
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.
我试图将 RewriteValve 移动到 META-INF 中的 config.xml 并将配置重写到 WEB-INF,但它的行为方式相同。
采纳答案by kamelot
I have found the solution, problem was in wrong/faulty rewrite.config file. Correct should be:
我找到了解决方案,问题出在错误/错误的 rewrite.config 文件中。正确的应该是:
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.
第一行是不应重写的枚举 URI。其他所有内容都将被重写为 index.html。
回答by Nicholas Hirras
Is this deployed as a java web app (WAR)? You could implement this in your web.xml:
这是否部署为 Java Web 应用程序 (WAR)?你可以在你的 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>
回答by mhvelplund
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.
我无法让它与 REQUEST_URI 一起工作,而且我也不喜欢将特定文件列入白名单,所以我以稍微不同的方式解决了它。