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

如何移除Angular应用URL末尾的#符号(如http://localhost:4200/#/)

移除Angular应用URL中的#符号

要把Angular应用的URL从http://localhost:4200/#/改为http://localhost:4200的形式,需完成以下两步操作:

1. 修改Angular路由配置

打开app-routing.module.ts文件,将路由模式切换为HTML5模式:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';

// 你的路由定义
const routes: Routes = [
  // 示例:{ path: '', component: HomeComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: false })], // 关闭哈希模式
  exports: [RouterModule],
  providers: [{ provide: LocationStrategy, useClass: PathLocationStrategy }] // 启用HTML5路径策略
})
export class AppRoutingModule { }

这一步会让Angular使用标准URL路径格式,不再依赖#符号。

2. 配置服务器重定向规则

修改路由后,刷新非根路径页面会出现404错误——这是因为服务器无法识别Angular的前端路由。需根据所用服务器添加重定向规则,将所有请求指向index.html:

开发服务器(Angular CLI)

默认无需额外配置;若部署在子路径,启动时需指定base-href:

ng serve --base-href /your-subpath/

Nginx

在服务器配置的server块中添加:

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

Apache

在项目根目录创建.htaccess文件,写入:

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

IIS

在项目根目录创建web.config文件,写入:

<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>

注意事项

  • 若应用部署在域名子路径下(如http://example.com/my-app/),构建时需指定--base-href /my-app/,同时服务器重定向路径要改为/my-app/index.html。
  • 完成配置后重启服务器即可生效。

内容的提问来源于stack exchange,提问作者Abu bakkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:55:21