问题 Tomcat 8 URL重写


我有一个AngularJS webapp和Jersey后端。我需要设置URL重写,因此除了给定的异常之外的所有内容都将被重写为Angular的index.html。

例如。:

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)

我已经设置了Tomcat 8 URL重写阀,如下所示:

的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>

CONF /卡塔利娜/ 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忽略了我的重写设置,没有重写,日志中没有错误/异常。我究竟做错了什么?提前致谢。

我试图将RewriteValve移动到META-INF中的config.xml并将配置重写为WEB-INF,但它的行为方式相同。


12432
2018-02-27 14:38


起源



答案:


我找到了解决方案,问题是在错误/错误的rewrite.config文件中。 正确的应该是:

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

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

第一行是枚举的URI,不应该重写。其他所有内容都将被重写为index.html。


9
2018-03-04 21:28



但为什么它有问题呢?我有同样的问题。 %{REQUEST_FILENAME}始终为NULL ... - Mario Eis
...和SCRIPT_FILENAME是正确的,但RewriteCond%{SCRIPT_FILENAME} -f抱怨资源中缺少前导/。它是一个Windows系统。所以路径是C:\ ...没有领先/ - Mario Eis
在我们的例子中,我们使用{REQUEST_URI}代替(REQUEST_FILENAME)。我们无法完全删除规则,因为我们无法加载应用程序本地的资产,但更改!-f和!-d以使用REQUEST_URI似乎工作,至少现在。 - Dave DuPlantis


答案:


我找到了解决方案,问题是在错误/错误的rewrite.config文件中。 正确的应该是:

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

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

第一行是枚举的URI,不应该重写。其他所有内容都将被重写为index.html。


9
2018-03-04 21:28



但为什么它有问题呢?我有同样的问题。 %{REQUEST_FILENAME}始终为NULL ... - Mario Eis
...和SCRIPT_FILENAME是正确的,但RewriteCond%{SCRIPT_FILENAME} -f抱怨资源中缺少前导/。它是一个Windows系统。所以路径是C:\ ...没有领先/ - Mario Eis
在我们的例子中,我们使用{REQUEST_URI}代替(REQUEST_FILENAME)。我们无法完全删除规则,因为我们无法加载应用程序本地的资产,但更改!-f和!-d以使用REQUEST_URI似乎工作,至少现在。 - Dave DuPlantis


这部署为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>

3
2018-02-27 18:08



谢谢Nicholas,这似乎是一个有趣的选择,但我已设法使用重写解决它。我有错误的rewrite.config文件。 - kamelot
这绝对是错误的解决方案。接受的答案是动态的,这个答案是硬编码的 - Talador12


我无法使用REQUEST_URI,我不喜欢将特定文件列入白名单,所以我解决了 方式略有不同


0
2018-06-30 13:34