Apache 憑藉卓越的可移植性(支持 30+ 作業系統),成為目前互聯網註冊域名中最廣泛使用的 Web 服務器。本文詳細講解如何通過修改服務器配置,啟用 CGI 程序與 Server-Side Include(SSI)以提供動態網頁內容。
假設 Apache 已安裝完成並能正常服務靜態頁面(可見默認測試頁)。基礎安裝僅支持靜態 HTML,需通過模組擴展功能。原始編譯通常包含 mod_include 與 mod_cgi 兩個模組,可通過 ./httpd -l 驗證。若缺失需重新編譯並包含這兩個模組。
Apache 主配置文件位於 conf/httpd.conf(Unix: /usr/local/apache/conf/,Windows: C:\Program Files\Apache\conf\)。純文本格式,可用 vi/Notepad 編輯。以 # 開頭的行為註釋,良好註釋習慣有助於維護。
httpd.conf,找到並取消註釋以下兩行:
AddType text/html .shtml
AddHandler server-parsed .shtml
AddType 指定 .shtml 文件以 text/html 類型傳輸;AddHandler 將文件內容交給 mod_include 處理。
<Directory> 區塊中的 Options 行,默認為:
Options Indexes FollowSymLinks MultiViews
在末尾添加 Includes:
Options Indexes FollowSymLinks MultiViews Includes
kill -HUP `cat /usr/local/apache/logs/httpd.pid`Apache -k restart在 htdocs 目錄創建 test.shtml:
<!--#include file="hello.txt" -->
The file hello.txt is <!--#fsize file="hello.txt" --> bytes long and it was last modified on <!--#flastmod file="hello.txt" -->
同目錄創建 hello.txt(內容任意)。訪問 https://localhost/test.shtml 應顯示文件大小與修改時間。
在 .htaccess 中添加:
XBitHack on
設置文件用戶可執行位(chmod +x file.shtml)後,Apache 將其視為 SSI 文件。XBitHack full 還會檢查組可執行位,並設置 Last-Modified 響應頭以支持緩存。注意:輪播廣告等動態內容不宜啟用組可執行位,否則導致緩存異常。
原始安裝 cgi-bin 目錄包含 test-cgi、printenv 兩個測試程序(有潛在安全風險,僅供測試)。
chmod +x script,Windows 通常不需此步)https://localhost:8080/cgi-bin/test-cgi(非 root 安裝需指定 8080 端口)ScriptAlias 指令控制,默認配置:
ScriptAlias /cgi-bin/ /usr/local/apache/cgi-bin/
該指令將 URL 路徑 /cgi-bin/ 映射至文件系統目錄,並標記為可執行目錄。
創建 how.sh:
#!/bin/sh
echo "Content-type: text/html"
echo ""
echo "How are you!"
賦予執行權限後訪問 https://localhost:8080/cgi-bin/how.sh。CGI 可使用任意系統支持語言編寫(Perl、Python、C 等)。
Apache 所有 SSI 指令詳見官方文檔。配置文件功能極其強大,建議深入閱讀隨版本附帶的核心/標準模組文檔,挖掘更多進階功能。