如何在IIS 10上部署Angular SSG(静态站点生成)?
解决Angular SSG部署IIS 10的路径映射问题
问题背景
Angular SSG生成的静态页面会采用page1/index.html的结构(对应预期访问路径/page1.html),直接部署到IIS后,访问/page1.html会返回404——因为IIS默认不会自动将这类请求映射到子文件夹下的index.html文件。
解决方案:配置URL重写规则
通过添加URL重写规则,让IIS自动将.html结尾的请求转发到对应子文件夹的index.html文件。
步骤1:安装URL重写模块
如果IIS未安装该模块,打开IIS管理器,进入「管理」-「Web平台安装程序」,搜索并安装URL Rewrite模块。
步骤2:添加web.config配置
在Angular项目打包后的dist根目录下创建(或修改)web.config文件,写入以下配置:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <!-- 处理SSG生成的html路径映射 --> <rule name="SSG HTML Route" stopProcessing="true"> <match url="^(.*)\.html$" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="{R:1}/index.html" /> </rule> <!-- SPA路由 fallback 规则(按需保留) --> <rule name="SPA Fallback" 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> <!-- 确保静态资源MIME类型正确 --> <staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> <mimeMap fileExtension=".svg" mimeType="image/svg+xml" /> </staticContent> </system.webServer> </configuration>
步骤3:验证部署效果
- 将
dist文件夹设置为IIS站点的物理路径 - 重启IIS站点,访问
/page1.html,确认能正常加载page1/index.html的内容 - 若仍出现404,检查URL重写模块是否安装成功,或web.config是否被IIS正确读取
关键说明
- 第一条规则专门匹配
.html结尾的请求,将xxx.html重写为xxx/index.html,完美适配Angular SSG的生成结构 - 第二条规则是SPA路由的 fallback 配置,如果项目同时包含单页应用路由逻辑,可保留该规则确保路由正常工作
- 静态文件MIME类型配置避免json、svg等资源因类型识别错误无法加载
内容的提问来源于stack exchange,提问作者Bruno Gallego
相关产品推荐
相关产品推荐

