Angular 4中移除URL#号后刷新页面报404问题求助
解决Angular 4移除URL#后刷新页面404的问题
为啥会出现这个问题?
当你去掉useHash: true、切换到PathLocationStrategy后,URL看起来和普通网站路径无异(比如/user/detail),但这些路径其实是Angular的客户端路由——服务器根本没有对应的物理文件或后端路由。刷新页面时,浏览器会直接向服务器请求这个路径,服务器找不到匹配的资源,自然就返回404了。
核心解决方案:配置服务器路由重写
你需要让服务器把所有非静态资源的请求,都转发到Angular的入口文件index.html,这样Angular就能接管路由、正确渲染对应页面了。下面是不同场景的具体配置方法:
1. 开发环境(Angular CLI内置服务器)
如果用ng serve启动开发服务,其实CLI已经默认处理了这个问题,刷新不会404。要是你用的是自定义Express开发服务器,可以这么搞:
- 先安装历史路由回退中间件:
npm install connect-history-api-fallback --save-dev - 在Express代码中添加配置:
const express = require('express'); const history = require('connect-history-api-fallback'); const app = express(); // 先启用回退中间件,处理客户端路由 app.use(history()); // 再托管Angular构建后的静态文件 app.use(express.static(__dirname + '/dist')); app.listen(3000, () => console.log('Server running on port 3000'));
2. 生产环境服务器配置
Apache服务器
在项目根目录(或网站根目录)创建.htaccess文件,写入以下规则:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # 直接访问index.html时不做处理 RewriteRule ^index\.html$ - [L] # 如果请求的不是文件或目录,转发到index.html RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule>
记得确保Apache开启了mod_rewrite模块。
Nginx服务器
在站点配置的location /块中修改为:
location / { # 先尝试访问文件、目录,找不到就转发到index.html try_files $uri $uri/ /index.html; }
修改后重启Nginx服务生效。
IIS服务器
- 先安装IIS官方的
URL Rewrite模块 - 在网站根目录创建
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>
额外提醒
- 确认Angular项目的
<base href="/">标签配置正确:如果你的应用部署在子目录(比如https://example.com/my-app/),需要把base href改成"/my-app/",避免路由跳转出错。 - 其他服务器(比如Tomcat)的配置思路一致:只要把所有非静态资源的请求转发到
index.html即可。
内容的提问来源于stack exchange,提问作者Anurag Gupta
相关产品推荐
相关产品推荐

