IIS虚拟空间配置SSI 支持.html的代码及详解

IIS(Internet Information Services)的 web.config 文件片段,主要用于启用服务器端包含(SSI,Server Side Includes)功能,让.shtml、.shtm和.html文件支持 SSI 指令(如#include)。以下是详细解析和注意事项:

一、配置各部分作用

  1. <staticContent>:MIME 类型配置

为.shtml和.shtm文件设置 MIME 类型为text/html,确保浏览器能正确识别并渲染为 HTML 页面(默认情况下 IIS 可能未配置这两个扩展名的 MIME 类型)。

  1. <handlers>:处理程序映射

为.shtml、.shtm、.html文件注册 SSI 处理程序:

    • 使用ServerSideIncludeModule模块和ssinc.dll(IIS 内置的 SSI 处理组件)解析文件中的 SSI 指令。
    • 限制请求方法为GET/HEAD,仅处理文件类型资源,且只需要 “读取” 权限。
  1. <serverSideInclude>:SSI 指令权限

明确允许这三类文件使用Include指令(SSI 核心指令,用于嵌入其他文件内容),避免 IIS 拦截或禁止该指令。

二、生效前提

  1. IIS 需安装 “Server Side Includes” 功能

在 Windows 服务器的 “服务器管理器”→“添加角色和功能”→“Web 服务器 (IIS)”→“应用程序开发” 中,勾选 **“Server Side Includes”** 组件。

  1. 站点权限配置

确保 IIS 应用程序池标识对相关文件(包括被#include引用的文件)有读取权限。

三、注意事项

  1. 性能影响

对.html文件启用 SSI 会导致 IIS 不再将其视为纯静态文件,而是通过ssinc.dll解析,可能轻微降低静态页面的响应速度。若仅需对.shtml/.shtm启用 SSI,可删除.html相关配置。

  1. 安全风险

避免在 SSI 中嵌入用户可控内容(如 URL 参数),防止 SSI 注入攻击(如#exec指令执行系统命令,但本配置仅允许Include指令,风险较低)。

  1. 配置简化

可通过通配符合并扩展名配置(如path="*.shtml,*.shtm,*.html"),减少重复配置: 

<add

name="SSI-all"

path="*.shtml,*.shtm,*.html"

verb="GET,HEAD"

modules="ServerSideIncludeModule"

scriptProcessor="%SystemRoot%\system32\inetsrv\ssinc.dll"

resourceType="File"

requireAccess="Read"

/>

<serverSideInclude>

<add fileExtension=".shtml,.shtm,.html" allowedDirectives="Include" />

</serverSideInclude>

四、测试验证

创建测试文件(如test.html),写入 SSI 指令: 

<!--#include file="header.html" -->

<p>主内容</p>

<!--#include file="footer.html" -->

访问该文件,若成功嵌入header.html和footer.html内容,说明配置生效。

最终精简的代码如何:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <!-- 处理程序映射:仅.html文件 -->
    <handlers>
      <add 
        name="SSI-html"
        path="*.html"
        verb="GET,HEAD"
        modules="ServerSideIncludeModule"
        scriptProcessor="%SystemRoot%\system32\inetsrv\ssinc.dll"
        resourceType="File"
        requireAccess="Read"
      />
    </handlers>
 
    <!-- 允许.html文件使用SSI的Include指令 -->
    <serverSideInclude>
      <add fileExtension=".html" allowedDirectives="Include" />
    </serverSideInclude>
  </system.webServer>
</configuration>
本文网址: https://www.gd230.com/a/26.html