如何移除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
相关产品推荐
相关产品推荐

