Angular应用部署IIS后%符号处理异常及服务器信息隐藏问题
解决方案:Angular 16部署IIS后%符号URL 400错误及服务器信息泄露问题
一、修复带%符号的URL 400错误
1. 允许IIS处理未转义的%字符
IIS默认会拦截包含未转义%的URL(因为标准URL中%需跟随两位十六进制编码),可通过Request Filtering开启允许:
- 打开IIS管理器,选中目标站点,双击Request Filtering
- 右侧点击Edit Feature Settings
- 勾选Allow unescaped percent characters,点击确定
2. 添加URL重写规则转义%字符
若上述设置仍无效,在web.config中添加转义规则(需放在Angular路由重写规则之前),将URL中的%转成合法的URL编码%25:
<system.webServer> <rewrite> <rules> <!-- 先转义%字符 --> <rule name="Escape Percent" stopProcessing="false"> <match url="^(.*)%(.*)$" /> <action type="Redirect" url="{R:1}%25{R:2}" redirectType="Permanent" /> </rule> <!-- 原有的Angular SPA路由重写规则 --> <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>
3. 排查URL-Scan干扰
若之前配置了URL-Scan,检查URL-Scan.ini中的相关参数:
- 确保
AllowPercent=1(允许%字符通过) - 若仍有冲突,可临时禁用URL-Scan模块,验证问题是否由其导致
二、隐藏服务器名称(移除Server响应头)
1. 通过web.config全局移除Server头
IIS 10.0.1709及以上版本支持直接移除Server头,在web.config中添加:
<system.webServer> <security> <requestFiltering removeServerHeader="true" /> </security> <!-- 可选:替换为自定义Server头(按需配置) --> <httpProtocol> <customHeaders> <add name="Server" value="Web Server" /> </customHeaders> </httpProtocol> </system.webServer>
2. 确保错误页不暴露服务器信息
- 在IIS管理器中,选中站点,双击Error Pages
- 点击右侧Edit Feature Settings,选择Custom error pages,将所有错误页指向本地静态文件(避免使用IIS默认错误页)
- 自定义错误页所在目录的web.config也要包含上述移除Server头的配置
测试验证
- 访问带%的URL(如
/test%route),确认返回200状态码并正常加载Angular页面 - 通过浏览器开发者工具查看响应头,确认
Server头已被移除或替换为自定义内容
内容的提问来源于stack exchange,提问作者falgun modi
相关产品推荐
相关产品推荐

