【发布时间】:2021-06-03 13:25:34
【问题描述】:
如果在我的 Angular 应用程序中找不到路由,我想发送 http 状态代码 404。直接使用 Angular 是不可能的,因为它是一个 SPA。如何告诉 seo 爬虫未找到的路由是 404?
【问题讨论】:
标签: angular apache http-status-code-404 single-page-application
如果在我的 Angular 应用程序中找不到路由,我想发送 http 状态代码 404。直接使用 Angular 是不可能的,因为它是一个 SPA。如何告诉 seo 爬虫未找到的路由是 404?
【问题讨论】:
标签: angular apache http-status-code-404 single-page-application
我发现了一个视频,谷歌的一个人说,至少谷歌机器人正确处理 javascript 重定向到 404: https://www.youtube.com/watch?v=vjj8B4sq0UI&t=30m15s
所以我添加了这个路由:
const routes: Routes = [
...
{
path: 'not-found-404',
component: NotFoundComponent
},
{
path: '**',
component: NotFoundComponent
},
];
所以所有未处理的路由都被重定向到NotFoundComponent。你可以find in-depth infos here
然后我更改了我的 apache 服务器配置,将状态码设置为 404,如果 /not-found-404 已加载
# my .htaccess file (before angular rewrites)
RewriteRule ^not-found-404(\?.*)?$ - [R=404] # Redirect status
ErrorDocument 404 /index.html
现在服务器返回状态码 404。然后将我的 Angular 应用程序加载为错误文档。
但是在应用内部路由时不会发生这种重写,因为在加载NotFoundComponent 时没有页面重新加载。所以我将此代码添加到ngOnInit 的NotFoundComponent
ngOnInit() {
this.activatedRoute.queryParams.subscribe(queryParams => {
if (!queryParams["404_status_code_refresh_done"]) {
location.href = "/not-found-404?404_status_code_refresh_done=true"
}
})
}
它使用参数重新加载页面以避免无限循环。这将返回状态码 404。当我想在我的应用程序中触发 404 时,我可以直接路由到“/not-found-404”,NotFoundComponent 会使用 404 状态码处理重新加载。
有人认为这种技术有什么缺点吗?感觉有点hacky,但它应该可以工作,对吧?
【讨论】: