【问题标题】:How to output http status code 404 in an Angular SPA (not Angular Universal)如何在 Angular SPA(不是 Angular Universal)中输出 http 状态码 404
【发布时间】:2021-06-03 13:25:34
【问题描述】:

如果在我的 Angular 应用程序中找不到路由,我想发送 http 状态代码 404。直接使用 Angular 是不可能的,因为它是一个 SPA。如何告诉 seo 爬虫未找到的路由是 404?

【问题讨论】:

    标签: angular apache http-status-code-404 single-page-application


    【解决方案1】:

    我发现了一个视频,谷歌的一个人说,至少谷歌机器人正确处理 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 时没有页面重新加载。所以我将此代码添加到ngOnInitNotFoundComponent

    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,但它应该可以工作,对吧?

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 2016-09-16
      • 2018-03-07
      • 2018-03-28
      • 1970-01-01
      • 2021-10-30
      • 2018-06-23
      • 2017-11-27
      • 2016-06-29
      相关资源
      最近更新 更多