任何人都可以就如何配置 Tomcat 以完全避免 404 提出建议,而不是在找不到页面时(特别是在应该触发 404 的情况下)返回 index.html 内容和 200 作为状态? 让我告诉你我为什么要这样做:
我们有 Angular 应用程序“www.app.exmpl/app”,当用户点击“www.app.exmpl/app”应用程序时正确显示并返回 200。返回的 index.html 包含 Angular 应用程序代码。
当用户点击“www.app.exmpl/app/some_unexisted_url_in_file_system_path”时,tomcat 会尝试查找可以提供此 url 的端点或 html 文件,并返回 404,并且在 web.xml 中我们有以下配置:
<error-page> <error-code>404</error-code> <location>/index.html</location> </error-page>
这会导致用户收到 404 响应,但网络应用程序仍会加载 正确,因为 index.html 中有 Angular 应用程序并且在加载页面后 将 url 重写为正确的 url,例如:“www.app.exmpl/app”。
- 当用户点击“www.app.exmpl/app/url_handled_by_angular_app”时,仍然找不到“url_handled_by_angular_app”下的页面或端点,因此 tomcat 将代码设置为 404 并呈现 index.html,返回给用户,并且在用户的电脑上,此响应呈现为 Angular 应用程序而无需重写 url,因为 Angular 应用程序知道如何处理此“url_handled_by_angular_app”路由。
所以总而言之,我只需要摆脱 404 并将它们全部替换为 200,并且在这种情况下只渲染 index.html 内容。这种情况的最佳做法是什么?
最佳答案
如果服务器上没有重定向规则,应用程序深层链接将无法工作。所有深层链接都必须由服务器重定向到应用程序 index.html
。
设置 tomcat 以重定向任何深层链接 -
- 在 server.xml 中配置 RewriteValve
- 在rewrite.config中写入重写规则
<强>1。在 server.xml 中配置 RewriteValve
编辑 ~/conf/server.xml 以在 Host 部分添加以下 Valve,如下所示 –
...
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
...
</Host>
...
<强>2。在rewrite.config中写入重写规则
创建目录结构 - ~/conf/Catalina/localhost/并在其中使用以下内容创建 rewrite.config 文件。注意 - 在这里,我将 /app
视为问题中提到的应用程序的上下文路径。
RewriteCond %{REQUEST_PATH} !-f
RewriteRule ^/app/(.*) /app/index.html
设置完成后重新启动 tomcat 服务器,您可以点击应用程序的深层链接,该链接将路由到 Angular 应用程序内的正确组件。
可以引用this post了解更多详情。
关于angular - 找不到页面时更改 tomcat 的行为 (404),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867279/