在Apache Tomcat 404深层链接问题上部署角度应用程序

问题描述 投票:7回答:2

我试图弄清楚如何设置Apache Tomcat服务器以提供具有深层链接的角度应用程序。例如:

当收到mysite.com/的请求时,静态服务器会定期返回index.html。但它拒绝mysite.com/heroes/42并返回404 - Not Found错误,除非它被配置为返回index.html。

我想在localhost / angular上提供角度应用程序,我试过以下:

1)构建角度应用:

ng build --prod --base-href .

2)将build文件夹的内容(默认值:dist)复制到$ ApacheLocation / webapps / angular

3)在$ ApacheLocation / conf / Catalina / localhost / rewrite.config中添加RewriteRules

# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]  
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d  
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^\/angular\/.*$ /angular/index.html

4)在主机标签下方添加阀门

 <Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true"> 
   <Valve className="org.apache.catalina.valves.rewrite.RewriteValve"/>

5)启动Tomcat服务器并转到localhost / angular会给我:

未捕获的SyntaxError:意外的令牌<用于所有.js包(例如main.bundle.js)

如果我不包含重写规则,tomcat将按预期提供localhost / angular,但会在深层链接上提供404。

我的设置配置:

  • tomcat版本9.0.0.M26
  • 角度版本4.4.2
  • @ angular / cli:1.4.2
  • 节点:8.5.0
  • npm:5.4.2
  • :linux x64
apache angular tomcat deployment angular-cli
2个回答
7
投票

我设法通过以下步骤解决了这个问题,例如http://localhost:8080/angular/player/detail/4

1)使用以下命令构建角度应用:ng build --prod -bh ./ -d / angular

2)将构建应用程序的内容复制到$ Apache Location / webapps / angular

3)重写规则:

RewriteCond %{REQUEST_PATH} !-f
RewriteRule ^/angular/(.*) /angular?path=$1

4)app.component.ts上的设置导航:

constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

ngOnInit() {
const path = this.activatedRoute.snapshot.queryParams['path'];
const navigateTo = '/' + path;

if (path) {
  this.router.navigate([navigateTo]);
}

}

你可以在这里找到测试项目:https://github.com/avuletica/test

重写规则的说明:

# %{REQUEST_PATH} corresponds to the full path that is used for mapping.
# ! NOT character 
# '-f' (is regular file) Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
# ^ matches the beginning of the string or line
# . matches any charceter except line breaks
# * match 0 or more of the preceding token

所以基本上如果没有文件/ angular / what tomcat将完整路径作为查询字符串发送到角度应用程序并从该查询param angular处理路由。


1
投票

在apache tomcat服务器上部署角度应用程序(使用PathLocationStrategy路由)时修复深层链接问题(8,9) -

  1. 在server.xml中配置RewriteValve
  2. 在rewrite.config中写入重写规则

server.xml -

...
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />

...
      </Host>
...

rewrite.config - (注意 - / hello /是tomcat上角度应用程序的上下文路径)

RewriteCond %{REQUEST_PATH} !-f
RewriteRule ^/hello/(.*) /hello/index.html

我在文章中记录了这个问题 - Fixing deep linking issue – Deploying angular application on Tomcat server

注意 - 实现此目的不需要客户端设置(除了来自CLI的默认配置)。所有客户端路由都是Angular Routing模块的句柄。

© www.soinside.com 2019 - 2024. All rights reserved.