雖然現代 Web 開發多用高級語言框架,但 C 語言 CGI 以極致性能、超低內存佔用、直接調用系統庫的優勢,在嵌入式 Web 界面、高頻交易網關、舊系統改造等場景仍不可替代。本文從 Apache 安裝配置到首個 CGI 程序編寫,提供完整落地指南。
httpd-2.4.x-win64-VC15.zip 解壓至 C:\Apache24httpd.exe -k install 安裝服務httpd.exe -k start 或服務管理器中啟動 Apache2.4https://localhost 見到 "It works!"conf/httpd.conf# 1. 載入 CGI 模塊(取消註釋)
LoadModule cgid_module modules/mod_cgid.so
# 2. 配置 CGI 腳本目錄
ScriptAlias /cgi-bin/ "C:/Apache24/cgi-bin/"
<Directory "C:/Apache24/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Require all granted
# 3. 關鍵:指定 .cgi/.exe 為可執行腳本
AddHandler cgi-script .cgi .exe
# 4. 允許 CGI 執行(防止 403 Forbidden)
Options +ExecCGI
</Directory>
mkdir C:\Apache24\cgi-bin # Windows 無需 chmod,確保 IIS_IUSRS / Users 有讀取/執行權限
hello.c#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// 1. 必須輸出 HTTP 頭(Content-Type + 空行)
printf("Content-Type: text/html; charset=utf-8\r\n\r\n");
// 2. 輸出 HTML 內容
printf("<!DOCTYPE html>\n");
printf("<html><head><title>C CGI Demo</title></head><body>\n");
printf("<h1>Hello from C CGI!</h1>\n");
printf("<p>Server time: ");
// 3. 示例:調用 C 庫函數獲取時間
time_t now = time(NULL);
printf("%s", ctime(&now));
printf("</p></body></html>\n");
return 0;
}
# GCC (MinGW) gcc hello.c -o hello.exe -static # MSVC (Visual Studio Developer Command Prompt) cl hello.c /Fehello.exe /MT
關鍵: 輸出文件名為 hello.exe,放入 C:\Apache24\cgi-bin\。
瀏覽器打開 https://localhost/cgi-bin/hello.exe 應顯示動態生成的 HTML 頁面。
| 變量 | 含義 | 示例 |
|---|---|---|
REQUEST_METHOD | HTTP 方法 | GET / POST |
QUERY_STRING | URL 參數(GET) | name=zhang&age=20 |
CONTENT_LENGTH | POST 數據長度 | 27 |
CONTENT_TYPE | POST 數據類型 | application/x-www-form-urlencoded |
HTTP_COOKIE | 客戶端 Cookie | session=abc123 |
REMOTE_ADDR | 客戶端 IP | 192.168.1.100 |