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

Angular中如何移除URL中的#符号?解决刷新页面404问题

移除Angular路由哈希后刷新404的解决办法

当你移除{useHash:true}并切换到PathLocationStrategy(HTML5模式)后,刷新页面出现404是因为:浏览器刷新时会直接向服务器请求当前URL对应的资源,但这些路由路径是Angular前端管理的,服务器上并没有对应的文件,因此返回404。解决核心是让服务器将所有非静态资源的请求重定向到Angular的index.html,由前端接管路由处理。

一、确保Angular项目配置正确

  1. 在app.module.ts中配置路径策略:
import { LocationStrategy, PathLocationStrategy } from '@angular/common';

@NgModule({
  // 其他模块、组件配置
  providers: [
    { provide: LocationStrategy, useClass: PathLocationStrategy }
  ]
})
export class AppModule { }
  1. 确认angular.json中的baseHref配置正确:
    如果项目部署在域名根路径,baseHref设为"/";如果是子路径(如https://example.com/my-app/),则设为"/my-app/"。

二、服务器端配置(关键步骤)

根据你使用的服务器,添加对应的重定向规则:

1. Nginx

修改站点配置文件,在location /块中添加try_files指令:

server {
  listen 80;
  server_name 你的域名;
  root /你的Angular项目dist目录绝对路径;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

修改后重启Nginx生效。

2. Apache

在项目dist目录下创建.htaccess文件,写入以下内容:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

注意:需确保Apache开启了mod_rewrite模块。

3. Node.js(Express)

在Express服务代码中添加中间件,将所有请求指向index.html:

const express = require('express');
const path = require('path');
const app = express();

// 托管Angular静态资源
app.use(express.static(path.join(__dirname, 'dist/你的项目名称')));

// 所有路由请求返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/你的项目名称/index.html'));
});

app.listen(3000, () => {
  console.log('服务器运行在3000端口');
});

4. IIS

在站点根目录创建web.config文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

完成以上配置后,刷新页面就不会出现404错误,Angular能正常处理前端路由。

内容的提问来源于stack exchange,提问作者Razeen Mohamed Rasheed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:02:58