Server Side Includes (SSI) 是一種伺服器端模板技術,在頁面發送給瀏覽器前,將指定檔案內容「包含」進當前頁面。類似 PHP 的 include,但由 Web 伺服器直接處理,不經 PHP 解析器,效能極高,適合靜態片段重用(頁首、頁尾、導航欄、廣告位等)。
| 指令 | 語法 | 用途 |
|---|---|---|
| include | 或 | 引入外部檔案內容(相對/絕對路徑) |
| echo | | 輸出環境變數(如 DATE_LOCAL、HTTP_USER_AGENT) |
| config | | 設定時間/大小顯示格式 |
| fsize | | 顯示檔案大小 |
| flastmod | | 顯示檔案最後修改時間 |
| exec | | 執行 Shell 命令(高風險,通常禁用) |
| set/if/elif/else/endif | XSSI 擴展指令 | 變數設定與條件判斷(Apache mod_include 支援) |
# httpd.conf 或 apache2.conf # 1. 載入模組 LoadModule include_module modules/mod_include.so # 2. 目錄權限啟用 IncludesOptions Indexes FollowSymLinks Includes AllowOverride All Require all granted # 3. 指定解析副檔名(建議 .shtml、.html 皆啟用) AddType text/html .shtml .html AddOutputFilter INCLUDES .shtml .html # 4. 可選:XSSI 擴展(支援變數/條件) # 已包含在 mod_include 中,無需額外載入
修改後重啟 Apache:systemctl restart httpd 或 apachectl graceful
# nginx.conf 或 site 配置
location / {
ssi on; # 啟用 SSI
ssi_last_modified on; # 傳送 Last-Modified 頭(利於快取)
# ssi_types text/html; # 預設僅 text/html,可擴展
# ssi_min_file_chunk 1k; # 小檔案直接內聯,減少系統調用
}
注意:Nginx SSI 不支援 exec、set 等進階指令,僅支援 include、echo、config 基礎功能。
<header class="site-header">
<h1><a href="/">MySite</a></h1>
<nav>
<a href="/">首頁</a>
<a href="/about">關於我們</a>
<!--#if expr="$HTTP_COOKIE / 'user_id='" -->
<a href="/dashboard">儀表板</a>
<a href="/logout">登出</a>
<!--#else -->
<a href="/login">登入</a>
<a href="/register">註冊</a>
<!--#endif -->
</nav>
</header>
<footer class="site-footer">
© <!--#echo var="DATE_LOCAL" --> MySite. All rights reserved.
<!--#config timefmt="%Y" --><!--#echo var="DATE_LOCAL" -->
</footer>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>SSI Demo</title></head><body>
<!--#include file="header.html" -->
<main>
<h2>歡迎來到 SSI Demo 頁面</h2>
<p>當前伺服器時間:<!--#echo var="DATE_LOCAL" --></p>
</main>
<!--#include virtual="/footer.html" -->
</body></html>
| 維度 | SSI | PHP include | Twig/Blade/Smarty |
|---|---|---|---|
| 執行層 | Web Server (Apache/Nginx) | PHP 解析器 | PHP 解析器 |
| 效能 | 極高(無 PHP 開銷) | 中(需啟動 PHP) | 中等(編譯快取後較快) |
| 動態能力 | 弱(僅環境變數、簡單條件) | 強(完整 PHP 語法) | 強(模板語法+繼承/區塊) |
| 適用場景 | 靜態片段、高流量靜態化頁面 | 通用 PHP 專案 | 複雜業務邏輯、前後端分離 |
| 快取友善 | 極佳(可直接 CDN 快取 .shtml) | 需額外快取層 | 需模板編譯快取 |
file="..." 相對於當前檔案目錄;virtual="/..." 相對於DocumentRoot。建議統一用 virtual[an error occurred while processing this directive],可用 自訂exec 指令;用戶上傳內容不可直接作為 SSI 檔案(防注入)Varnish、Nginx (ngx_http_esi_module)、Cloudflare Workers 支援 ESI,語法類似 SSI 但更強大:
<esi:include src="/fragment/header" />
<esi:vars>$(HTTP_COOKIE{user_id})</esi:vars>
<esi:choose>
<esi:when test="$(HTTP_COOKIE{user_id})">...</esi:when>
<esi:otherwise>...</esi:otherwise>
</esi:choose>
ESI 在 CDN/反向代理層組裝頁面,實現「動態片段 + 靜態整頁快取」的最佳平衡,是高併發架構的主流選擇。
SSI 雖屬老派技術,但在「靜態站點生成」「輕量級動態片段」「遷移舊專案」等場景依然實用。配合現代 CDN/ESI 架構,能以極低成本實現高效能頁面組裝。