Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 支持 CGI 與 SSI 動態內容完整配置教程

編輯:關於伺服器

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 編輯。以 # 開頭的行為註釋,良好註釋習慣有助於維護。

啟用 SSI 支持

方法一:標準配置

  1. 編輯 httpd.conf,找到並取消註釋以下兩行:
    AddType text/html .shtml
    AddHandler server-parsed .shtml
    AddType 指定 .shtml 文件以 text/html 類型傳輸;AddHandler 將文件內容交給 mod_include 處理。
  2. 尋找 <Directory> 區塊中的 Options 行,默認為:
    Options Indexes FollowSymLinks MultiViews
    在末尾添加 Includes:
    Options Indexes FollowSymLinks MultiViews Includes
  3. 重啟 Apache 生效:
    • Unix: kill -HUP `cat /usr/local/apache/logs/httpd.pid`
    • Windows: Apache -k restart

驗證 SSI

在 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 應顯示文件大小與修改時間。

方法二:XBitHack 機制

在 .htaccess 中添加:

XBitHack on

設置文件用戶可執行位(chmod +x file.shtml)後,Apache 將其視為 SSI 文件。XBitHack full 還會檢查組可執行位,並設置 Last-Modified 響應頭以支持緩存。注意:輪播廣告等動態內容不宜啟用組可執行位,否則導致緩存異常。

啟用 CGI 支持

原始安裝 cgi-bin 目錄包含 test-cgi、printenv 兩個測試程序(有潛在安全風險,僅供測試)。

  1. 確保腳本文件具有執行權限(Unix: chmod +x script,Windows 通常不需此步)
  2. 驗證內建程序:https://localhost:8080/cgi-bin/test-cgi(非 root 安裝需指定 8080 端口)
  3. CGI 支持由 ScriptAlias 指令控制,默認配置:
    ScriptAlias /cgi-bin/ /usr/local/apache/cgi-bin/
    該指令將 URL 路徑 /cgi-bin/ 映射至文件系統目錄,並標記為可執行目錄。

自定義 CGI 腳本示例

創建 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 指令詳見官方文檔。配置文件功能極其強大,建議深入閱讀隨版本附帶的核心/標準模組文檔,挖掘更多進階功能。

Copyright © Windows教程網 All Rights Reserved