Apache/CGI
外觀
< Apache
CGI (通用閘道器介面) 是一種標準,它允許 Apache 執行一些程式,這些程式可以用任何程式語言編寫 (Bash, C, Java, Perl, PHP, Python...),只要它可執行並符合某些輸入/輸出約束。
為了使 Apache 解釋指令碼,需要在站點配置中進行一些設定。
指令(來自 httpd.conf)
ScriptAlias /cgi-bin/ ''/scripts path/''
指定 Apache 允許執行 CGI 指令碼的資料夾名稱。 [1]
Unix 示例
ScriptAlias /cgi-bin/ /var/www/cgi-bin
Windows 示例,使用 URL 格式(沒有反斜槓)
ScriptAlias /cgi-bin/ "C:/wamp/bin/apache/apache2.2.27/cgi-bin/"
實際上,路徑 /cgi-bin/ 並不真正存在,它被重定向到由指令設定的指令碼路徑,並且它允許編寫一些類似 http://server/cgi-bin/my_script 的 URL。
以下子句在 /var/www/cgi-bin 中啟用選項 ExecCGI,這將授權 Apache 在伺服器上執行一些指令碼
<Directory /var/www/cgi-bin>
Options ExecCGI
</Directory>
例如,如果一個指令碼名為 essai.cgi 位於 /home/httpd/cgi-bin 中
<Directory /home/httpd/cgi-bin>
Options ExecCGI
</Directory>
然後,呼叫 URL:http://serveur/cgi-bin/essai.cgi
此子句允許選擇將被授權的副檔名,例如
AddHandler cgi-script .cgi .exe .pl .py .vbs
在 Apache 配置中,Windows 上的完整示例
ScriptAlias /cgi-bin/ "E:/www/cgi-bin/"
<Directory "E:/www/cgi-bin/">
Options FollowSymLinks Indexes
AllowOverride All
Order deny,allow
Allow from all
Require all granted
</Directory>
在 E:/www/cgi-bin/.htaccess 中
AddHandler cgi-script .cgi .exe .pl .py .vbs
主要約束與程式輸出有關。如果 CGI 指令碼在其標準輸出上生成一些資料,它必須在之前顯示一個 HTTP 頭,以便識別它們。
#!/bin/bash
# Header
echo "Content-type: text/html"
# Header end
echo ""
# Content to display in the navigator
echo "<html><body>Hello World!</body></html>"
此指令碼生成一個 HTML 頁面。
#!c:/perl/perl/bin/perl.exe -w
use CGI;
my $query = new CGI;
my $Name = $query->param('Name');
print $query->header();
print "Hello World!"
#!C:\Program Files (x86)\Python\python.exe
# -*- coding: UTF-8 -*-
print "Content-Type: text/plain;charset=utf-8"
print
print "Hello World!"
適用於 Windows。 [2]
'!c:/windows/system32/cscript //nologo
Wscript.Echo "Content-type: text/html" & vbLF & vbLF
WScript.Echo "Hello World!"
Wscript.Quit 0
- 錯誤 500 伺服器錯誤!: 將
Deny from all替換為Allow from all。
或
# setsebool -P httpd_enable_cgi 1 # chcon -R -t httpd_sys_script_exec_t cgi-bin/your_script.cgi
- 錯誤 403 禁止訪問: 無法列出此資料夾,因此直接呼叫其檔案。
- 如果檔案原始碼出現在瀏覽器中:.htaccess 設定不正確。
- 無法建立子程序: 替換 shebang 之後的路徑。例如
#!/usr/bin/perl替換為#!c:/perl/perl/bin/perl.exe -w。#!/usr/bin/env python替換為#!C:\Program Files (x86)\Python\python.exe。
- 指令碼輸出結束前出現標題: 缺少標題(例如:將匯入移動到
print "Content-Type: text/plain;charset=utf-8"之前)。但也可能是指令碼語言中編譯錯誤的症狀。 - 指令碼中的格式錯誤的標題:錯誤的標題: : 標題不適合(例如:如果之後有
print "<html>",則將#print "Content-Type: text/plain;charset=utf-8"替換為print "Content-type: text/html\n\n")。
否則,請檢視 Apache 日誌...