Angular带通配符路由时,如何配置/3rdpartylicenses.txt指向服务器文件
解决Angular路由拦截3rdpartylicenses.txt的问题
方法1:调整路由顺序,用重定向规则
Angular路由是按顺序匹配的,把3rdpartylicenses.txt的规则放在通配符/:token前面,就能优先匹配,避免被FeedSelectorComponent拦截。注意加上pathMatch: 'full'确保完全匹配路径:
const routes: Routes = [ // 先匹配许可证文件路径 { path: '3rdpartylicenses.txt', redirectTo: '/3rdpartylicenses.txt', pathMatch: 'full' }, // 再处理token通配符路由 { path: ':token', component: FeedSelectorComponent }, // 其他路由规则放后面 ];
如果之前这么配没生效,可能是Angular路由的重定向还在内部处理,没直接指向服务器文件,那就换下面的方法。
方法2:用空组件直接跳转文件
搞个空组件专门处理这个跳转,步骤很简单:
- 生成空组件:
ng generate component license-redirect --inline-template --inline-style
- 修改组件代码,初始化时直接跳转到服务器根目录的许可证文件:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-license-redirect', template: '', styles: [] }) export class LicenseRedirectComponent implements OnInit { ngOnInit(): void { window.location.href = '/3rdpartylicenses.txt'; } }
- 把这个组件和
3rdpartylicenses.txt路径绑定,放在通配符路由前面:
const routes: Routes = [ { path: '3rdpartylicenses.txt', component: LicenseRedirectComponent }, { path: ':token', component: FeedSelectorComponent }, ];
这样用户访问https://myapp/mycontent/3rdpartylicenses.txt时,会触发这个组件,直接跳转到服务器根目录的文件,绕开Angular路由拦截。
方法3:服务器端配置(最省心)
如果能改服务器配置,直接让服务器优先处理3rdpartylicenses.txt的请求,根本不让Angular路由碰它。比如Nginx这么配:
location /3rdpartylicenses.txt { root /你的dist文件夹路径; try_files $uri =404; } location / { try_files $uri $uri/ /index.html; }
Apache的话,可以在.htaccess里加规则,优先返回这个文件,不用走Angular的入口页。
内容的提问来源于stack exchange,提问作者UncleBob
相关产品推荐
相关产品推荐

