Angular应用部署IIS后刷新报404/500错误求助
解决Angular在IIS子目录部署后刷新404/500的问题
这是Angular部署到IIS子目录时很常见的坑,核心问题是你的配置没和WebApp这个子目录路径对齐,导致前端路由和IIS的重写规则不匹配。我帮你一步步修正:
1. 先改对index.html里的base href
你现在设的<base href="/">是指向网站根目录,但你的应用实际部署在/WebApp/子目录下,这会让Angular的路由解析完全跑偏——刷新时浏览器请求的路径根本没对应到子目录里的资源。
直接修改成:
<base href="/WebApp/">
改完记得重新构建Angular应用(比如执行ng build --prod),再把构建好的产物重新部署到IIS的WebApp目录里。
2. 调整web.config的重写规则
当前的重写规则逻辑是对的,但路径匹配没贴合子目录场景,导致IIS找不到index.html。分两种情况调整:
情况1:web.config放在网站根目录
如果你的web.config是放在IIS网站的根目录下,要明确匹配WebApp子目录的路径:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <directoryBrowse enabled="true" /> <rewrite> <rules> <rule name="Angular Routes" stopProcessing="true"> <!-- 匹配WebApp子目录下的所有请求路径 --> <match url="^WebApp/(.*)" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <!-- 重写到WebApp下的index.html --> <action type="Rewrite" url="/WebApp/index.html" /> </rule> </rules> </rewrite> <!-- 启用默认文档,访问/WebApp/时自动加载index.html --> <defaultDocument> <files> <add value="index.html" /> </files> </defaultDocument> </system.webServer> </configuration>
情况2:web.config放在WebApp子目录下
如果把web.config直接放在WebApp目录里,写法更简洁,用相对路径指向当前目录的index.html:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <directoryBrowse enabled="true" /> <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> <!-- 用相对路径指向当前目录的index.html --> <action type="Rewrite" url="./index.html" /> </rule> </rules> </rewrite> <defaultDocument> <files> <add value="index.html" /> </files> </defaultDocument> </system.webServer> </configuration>
3. 检查IIS的URL Rewrite模块
如果改完还是报错,先确认你的IIS服务器有没有装URL Rewrite模块:
- 打开IIS管理器,看服务器功能列表里有没有这个模块;
- 如果没有,得去微软官网下载对应IIS版本的模块安装,装完重启IIS再测试。
最后验证
完成配置后测试这几个场景:
- 访问
http://miweb.es/WebApp/能正常加载应用; - 跳转到路由
http://miweb.es/WebApp/download(注意不用带index.html,Angular路由会自动处理); - 刷新这个路由页面,不会再出现404/500错误。
内容的提问来源于stack exchange,提问作者Eladerezador
相关产品推荐
相关产品推荐

