You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中针对未找到页面返回404状态码?

如何为Angular的404组件返回真实404状态码

1. 服务器端渲染(Angular Universal)场景

如果你的应用使用Angular Universal做服务端渲染,可直接在PageNotFoundComponent中设置响应状态码:

  • 在组件中注入RESPONSE对象并设置状态码:
import { Component, Inject, OnInit } from '@angular/core';
import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { Response } from 'express';

@Component({
  selector: 'app-page-not-found',
  templateUrl: './not-found-page.component.html',
  styleUrls: ['./not-found-page.component.css']
})
export class PageNotFoundComponent implements OnInit {
  constructor(@Inject(RESPONSE) private response: Response) {}

  ngOnInit(): void {
    // 设置HTTP 404状态码
    this.response.status(404);
  }
}

服务端渲染该组件时,会在HTTP响应头中返回404状态码,让谷歌爬虫识别到真实的404,避免软404问题。

2. 纯客户端渲染(CSR)场景

纯SPA的客户端路由仅在浏览器内处理,首次请求不存在的路径时,服务器通常返回状态码200的index.html,这会导致软404。需通过服务器配置解决:

Nginx配置示例

修改站点配置,针对非静态资源、非有效路由的请求返回404状态码:

server {
  listen 80;
  server_name your-domain.com;
  root /path/to/your/angular/dist;
  index index.html;

  # 处理静态资源缓存
  location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
  }

  # 匹配有效路由(需根据你的实际路由调整)
  location / {
    try_files $uri $uri/ @404;
  }

  # 返回404状态码并加载Angular 404组件
  location @404 {
    return 404 /index.html;
  }
}

Apache配置示例

修改.htaccess文件:

RewriteEngine On
# 放行静态资源
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# 排除有效路由(需替换为你的实际路由前缀)
RewriteCond %{REQUEST_URI} !^/(home|about|contact|api) [NC]
# 返回404状态码
RewriteRule ^ - [R=404,L]

# 其他请求指向index.html
RewriteRule ^ index.html [L]

关键注意点

  • 纯CSR场景下,仅靠客户端代码无法修改HTTP响应状态码,必须依赖服务器配置。
  • 404页面内容需明确告知用户页面不存在,避免谷歌误判为正常页面。

内容的提问来源于stack exchange,提问作者Sebastián Rojas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:54:56