目录 搜索
首页 版本说明 从1.3升级到2.0 编译时配置的改变 运行时配置的改变 杂项变化 第三方模块 从 2.0 升级到 2.2 编译时配置的改变 运行时配置的改变 杂项变化 第三方模块 Apache 2.1/2.2 版本的新特性 核心增强 模块增强 程序增强 针对模块开发者的变化 Apache 2.0 版本的新特性 核心的增强 模块的增强 Apache许可证 参考手册 编译与安装 针对心急者的概述 要求 下载 解压 配置源代码树 编译 安装 配置 测试 升级 启动 Apache是怎样启动的 启动时发生错误 随系统启动时启动 额外信息 停止与重新启动 简介 立即停止 优雅重启 立即重启 优雅停止 附录:信号和竞争条件 运行时配置指令 主配置文件 配置文件的语法 模块 指令的作用域 .htaccess文件 配置段 配置段(容器)的类型 文件系统和网络空间 虚拟主机 代理 允许使用哪些指令? 配置段的合并 内容缓冲 简介 缓冲概述 安全方面的考虑 文件句柄缓冲 内存缓冲 磁盘缓冲 服务器全局配置 服务器标识 文件定位 限制资源的使用 日志文件 安全警告 错误日志 访问日志 日志滚动 管道日志 虚拟主机 其他日志文件 从URL到文件系统的映射 相关模块和指令 DocumentRoot DocumentRoot以外的文件 用户目录 URL重定向 反向代理 重写引擎 File Not Found 安全方面的提示 保持不断更新和升级 ServerRoot目录的权限 服务器端包含 关于CGI 未指定为脚本的CGI 指定为脚本的CGI 其他动态内容的来源 系统设置的保护 默认配置下服务器文件的保护 观察日志文件 动态共享对象(DSO) 实现 用法概要 背景知识 优点和缺点 内容协商 关于内容协商 Apache中的内容协商 协商的方法 打乱品质值 透明内容协商的扩展 超链和名称转换说明 缓冲说明 更多信息 自定义错误响应 行为 配置 自定义错误响应与重定向 地址和端口绑定 概述 针对IPv6的特殊考虑 怎样与虚拟主机协同工作 多路处理模块(MPM) 简介 选择一个MPM 默认的MPM 环境变量 设置环境变量 使用环境变量 用于特殊目的的环境变量 示例 处理器的使用 什么是处理器? 例子 程序员注意事项 过滤器 Apache2中的过滤器 智能过虑 使用过滤器 CGI脚本的Suexec执行 开始之前 suEXEC的安全模型 配置和安装suEXEC 启用和禁用suEXEC 使用suEXEC 调试suEXEC 谨防Jabberwock:警告和举例 性能调整 硬件和操作系统 运行时的配置 编译时的配置 附录:踪迹的详细分析 URL重写指南 mod_rewrite简介 实践方案 URL的规划 内容的处理 对访问的限制 其他 虚拟主机文档 总述 虚拟主机支持 配置指令 基于主机名的虚拟主机 基于域名的虚拟主机和基于IP的虚拟主机比较 使用基于域名的虚拟主机 与旧版浏览器的兼容性 基于IP地址的虚拟主机 系统需求 如何配置Apache 设置多个守护进程 配置拥有多个虚拟主机的单一守护进程 动态配置大量虚拟主机 动机 概述 简单的动态虚拟主机 一个实际的个人主页系统 在同一个服务器上架设多个主机的虚拟系统 更为有效的基于IP地址的虚拟主机 使用老版本的Apache 使用mod_rewrite实现简单的动态虚拟主机 使用mod_rewrite的个人主页系统 使用独立的虚拟主机配置文件 虚拟主机的普通配置示例 在一个IP地址上运行多个基于域名的web站点 在多于一个IP的情况下使用基于域名的虚拟主机 在不同的IP的地址(比如一个内部和一个外部地址)上提供相同的内容 在不同的端口上运行不同的站点 建立基于IP的虚拟主机 混用基于端口和基于IP的虚拟主机 混用基于域名和基于IP的虚拟主机 将虚拟主机和代理模块一起使用 使用默认虚拟主机 将一个基于域名的虚拟主机移植为一个基于IP的虚拟主机 使用ServerPath指令 深入讨论虚拟主机的匹配 解析配置文件 虚拟主机匹配 小技巧 文件描述符限制 关于DNS和Apache 一个简单示例 拒绝服务 "主服务器"地址 避免这些问题的小技巧 附录:进一步的提示 常见问题 概述 SSL/TLS 加密 概述 文档 mod_ssl 绪论 密码技术 证书 安全套接字层(SSL) 参考 兼容性 配置指令 环境变量 自定义日志功能 如何... 加密方案和强制性高等级安全 客户认证和访问控制 常见问题解答 About The Module Installation Configuration Certificates The SSL Protocol mod_ssl Support 如何.../指南 概述 认证 相关模块和指令 简介 先决条件 启用认证 允许多人访问 可能存在的问题 其他认证方法 更多信息 CGI动态页面 简介 配置Apache以允许CGI 编写CGI程序 程序还是不能运行! 幕后是怎样操作的? CGI模块/库 更多信息 服务器端包含 简介 什么是SSI? 配置服务器以允许SSI 基本SSI指令 附加的例子 我还能设置其它什么? 执行命令 高级SSI技术 总结 .htaccess文件 .htaccess文件 工作原理和使用方法 (不)使用.htaccess文件的场合 指令的生效 认证举例 服务器端包含(SSI)举例 CGI举例 疑难解答 用户网站目录 用户网站目录 用UserDir设置文件路径 限定哪些用户可以使用此功能 启用对每个用户都有效的cgi目录 允许用户改变配置 对特定平台的说明 概述 Microsoft Windows 其他平台 在Microsoft Windows中使用Apache 对操作系统的要求 下载 Apache for Windows 安装 Apache for Windows 配置 Apache for Windows 以服务方式运行 Apache for Windows 作为控制台程序运行Apache 测试安装 编译Windows下的Apache 系统要求 命令行编译 Developer Studio集成开发环境的工作区编译 项目组件 在Novell NetWare平台上使用Apache Requirements Downloading Apache for NetWare Installing Apache for NetWare Running Apache for NetWare Configuring Apache for NetWare Compiling Apache for NetWare 在HP-UX中运行Apache The Apache EBCDIC Port Overview of the Apache EBCDIC Port Design Goals Technical Solution Porting Notes Document Storage Notes Apache Modules' Status Third Party Modules' Status 服务器与支持程序 概述 httpd 语法 选项 ab 语法 选项 Bugs apachectl 语法 选项 apxs 语法 选项 举例 configure 语法 选项 环境变量 dbmmanage 语法 选项 Bugs htcacheclean 语法 选项 返回值 htdbm 语法 选项 Bugs 返回值 举例 安全方面的考虑 限制 htdigest 语法 选项 htpasswd 语法 选项 返回值 举例 安全方面的考虑 限制 logresolve 语法 选项 rotatelogs 语法 选项 Portability suexec 语法 选项 其他程序 log_server_status split-logfile 杂项文档 概述 相关标准 HTTP推荐标准 HTML推荐标准 认证 语言/国家代码 Apache 模块 描述模块的术语 说明 状态 源代码文件 模块标识符 兼容性 描述指令的术语 说明 语法 默认值(Default) 作用域(Context) 覆盖项(Override) 状态 模块(Module) 兼容性(Compatibility) Apache核心(Core)特性 AcceptFilter AcceptPathInfo AccessFileName AddDefaultCharset AddOutputFilterByType AllowEncodedSlashes AllowOverride AuthName AuthType CGIMapExtension ContentDigest DefaultType <Directory> <DirectoryMatch> DocumentRoot EnableMMAP EnableSendfile ErrorDocument ErrorLog FileETag <Files> <FilesMatch> ForceType HostnameLookups <IfDefine> <IfModule> Include KeepAlive KeepAliveTimeout <Limit> <LimitExcept> LimitInternalRecursion LimitRequestBody LimitRequestFields LimitRequestFieldSize LimitRequestLine LimitXMLRequestBody <Location> <LocationMatch> LogLevel MaxKeepAliveRequests NameVirtualHost Options Require RLimitCPU RLimitMEM RLimitNPROC Satisfy ScriptInterpreterSource ServerAdmin ServerAlias ServerName ServerPath ServerRoot ServerSignature ServerTokens SetHandler SetInputFilter SetOutputFilter TimeOut TraceEnable UseCanonicalName UseCanonicalPhysicalPort <VirtualHost> Apache MPM 公共指令 AcceptMutex CoreDumpDirectory EnableExceptionHook GracefulShutdownTimeout Group Listen ListenBackLog LockFile MaxClients MaxMemFree MaxRequestsPerChild MaxSpareThreads MinSpareThreads PidFile ReceiveBufferSize ScoreBoardFile SendBufferSize ServerLimit StartServers StartThreads ThreadLimit ThreadsPerChild ThreadStackSize User Apache MPM beos MaxRequestsPerThread CoreDumpDirectory Group Listen ListenBacklog MaxClients MaxMemFree MaxSpareThreads MinSpareThreads PidFile ReceiveBufferSize ScoreBoardFile SendBufferSize StartThreads User Apache MPM event AcceptMutex CoreDumpDirectory EnableExceptionHook Group Listen ListenBacklog LockFile MaxClients MaxMemFree MaxRequestsPerChild MaxSpareThreads MinSpareThreads PidFile ScoreBoardFile SendBufferSize ServerLimit StartServers ThreadLimit ThreadsPerChild ThreadStackSize User Apache MPM netware MaxThreads Listen ListenBacklog MaxMemFree MaxRequestsPerChild MaxSpareThreads MinSpareThreads ReceiveBufferSize SendBufferSize StartThreads ThreadStackSize Apache MPM os2 Group Listen ListenBacklog MaxRequestsPerChild MaxSpareThreads MinSpareThreads PidFile ReceiveBufferSize SendBufferSize StartServers User Apache MPM prefork 工作方式 MaxSpareServers MinSpareServers AcceptMutex CoreDumpDirectory EnableExceptionHook Group Listen ListenBacklog LockFile MaxClients MaxMemFree MaxRequestsPerChild PidFile ReceiveBufferSize ScoreBoardFile SendBufferSize ServerLimit StartServers User Apache MPM winnt Win32DisableAcceptEx CoreDumpDirectory Listen ListenBacklog MaxMemFree MaxRequestsPerChild PidFile ReceiveBufferSize ScoreBoardFile SendBufferSize ThreadLimit ThreadsPerChild ThreadStackSize Apache MPM worker 工作方式 AcceptMutex CoreDumpDirectory EnableExceptionHook Group Listen ListenBacklog LockFile MaxClients MaxMemFree MaxRequestsPerChild MaxSpareThreads MinSpareThreads PidFile ReceiveBufferSize ScoreBoardFile SendBufferSize ServerLimit StartServers ThreadLimit ThreadsPerChild ThreadStackSize User Apache Module mod_actions Action指令 Script指令 Apache Module mod_alias 处理顺序 Alias AliasMatch Redirect RedirectMatch RedirectPermanent RedirectTemp ScriptAlias ScriptAliasMatch Apache Module mod_asis 用法 Apache Module mod_auth_basic AuthBasicAuthoritative AuthBasicProvider Apache Module mod_auth_digest 使用摘要认证 配合 MS Internet Explorer 6 工作 AuthDigestAlgorithm AuthDigestDomain AuthDigestNcCheck AuthDigestNonceFormat AuthDigestNonceLifetime AuthDigestProvider AuthDigestQop AuthDigestShmemSize Apache Module mod_authn_alias 示例 <AuthnProviderAlias> Apache Module mod_authn_anon 示例 Anonymous Anonymous_LogEmail Anonymous_MustGiveEmail Anonymous_NoUserID Anonymous_VerifyEmail Apache Module mod_authn_dbd 配置示例 AuthDBDUserPWQuery AuthDBDUserRealmQuery Apache Module mod_authn_dbm AuthDBMType AuthDBMUserFile Apache Module mod_authn_default AuthDefaultAuthoritative Apache Module mod_authn_file AuthUserFile Apache Module mod_authnz_ldap Contents Operation The require Directives 举例 Using TLS Using SSL Using Microsoft FrontPage with mod_authnz_ldap AuthLDAPBindDN AuthLDAPBindPassword AuthLDAPCharsetConfig AuthLDAPCompareDNOnServer AuthLDAPDereferenceAliases AuthLDAPGroupAttribute AuthLDAPGroupAttributeIsDN AuthLDAPRemoteUserIsDN AuthLDAPUrl AuthzLDAPAuthoritative Apache Module mod_authz_dbm AuthDBMGroupFile AuthzDBMAuthoritative AuthzDBMType Apache Module mod_authz_default AuthzDefaultAuthoritative Apache Module mod_authz_groupfile AuthGroupFile AuthzGroupFileAuthoritative Apache Module mod_authz_host Allow Deny Order Apache Module mod_authz_owner 配置示例 AuthzOwnerAuthoritative Apache Module mod_authz_user AuthzUserAuthoritative Apache Module mod_autoindex Autoindex Request Query Arguments AddAlt AddAltByEncoding AddAltByType AddDescription AddIcon AddIconByEncoding AddIconByType DefaultIcon HeaderName IndexIgnore IndexOptions IndexOrderDefault IndexStyleSheet ReadmeName Apache Module mod_cache Related Modules and Directives 配置示例 CacheDefaultExpire CacheDisable CacheEnable CacheIgnoreCacheControl CacheIgnoreHeaders CacheIgnoreNoLastMod CacheLastModifiedFactor CacheMaxExpire CacheStoreNoStore CacheStorePrivate Apache Module mod_cern_meta MetaDir MetaFiles MetaSuffix Apache Module mod_cgi CGI 环境变量 CGI 脚本的调试 ScriptLog ScriptLogBuffer ScriptLogLength Apache Module mod_cgid ScriptSock ScriptLog ScriptLogBuffer ScriptLogLength Apache Module mod_charset_lite Common Problems CharsetDefault CharsetOptions CharsetSourceEnc Apache Module mod_dav Enabling WebDAV Security Issues Complex Configurations Dav DavDepthInfinity DavMinTimeout Apache Module mod_dav_fs DavLockDB Apache Module mod_dav_lock DavGenericLockDB Apache Module mod_dbd Connection Pooling Apache DBD API SQL Prepared Statements DBDExptime DBDKeep DBDMax DBDMin DBDParams DBDPersist DBDPrepareSQL DBDriver Apache Module mod_deflate 配置举例 启用压缩 代理服务器 DeflateBufferSize DeflateCompressionLevel DeflateFilterNote DeflateMemLevel DeflateWindowSize Apache Module mod_dir DirectoryIndex DirectorySlash Apache Module mod_disk_cache CacheDirLength CacheDirLevels CacheMaxFileSize CacheMinFileSize CacheRoot Apache Module mod_dumpio 启用dumpio支持 DumpIOInput DumpIOOutput Apache Module mod_echo ProtocolEcho Apache Module mod_env PassEnv SetEnv UnsetEnv Apache Module mod_example Compiling the example module Using the mod_example Module Example Apache Module mod_expires 交替间隔语法 ExpiresActive ExpiresByType ExpiresDefault Apache Module mod_ext_filter 举例 ExtFilterDefine ExtFilterOptions Apache Module mod_file_cache Using mod_file_cache CacheFile MMapFile Apache Module mod_filter Smart Filtering Filter Declarations Configuring the Chain Examples Protocol Handling FilterChain FilterDeclare FilterProtocol FilterProvider FilterTrace Apache Module mod_headers 处理顺序 前处理和后处理 举例 Header RequestHeader Apache Module mod_ident IdentityCheck IdentityCheckTimeout Apache Module mod_imagemap New Features Imagemap File Example Mapfile Referencing your mapfile ImapBase ImapDefault ImapMenu Apache Module mod_include Enabling Server-Side Includes PATH_INFO with Server Side Includes Basic Elements Include Variables Variable Substitution Flow Control Elements SSIEndTag SSIErrorMsg SSIStartTag SSITimeFormat SSIUndefinedEcho XBitHack Apache Module mod_info 安全问题 选择哪些信息可以被显示 已知的局限 AddModuleInfo Apache Module mod_isapi 用法 附加注释 程序员注记 ISAPIAppendLogToErrors ISAPIAppendLogToQuery ISAPICacheFile ISAPIFakeAsync ISAPILogNotSupported ISAPIReadAheadBuffer Apache Module mod_ldap 示例配置 LDAP 连接池 LDAP 缓冲 使用SSL/TLS SSL/TLS 证书 LDAPCacheEntries LDAPCacheTTL LDAPConnectionTimeout LDAPOpCacheEntries LDAPOpCacheTTL LDAPSharedCacheFile LDAPSharedCacheSize LDAPTrustedClientCert LDAPTrustedGlobalCert LDAPTrustedMode LDAPVerifyServerCert Apache Module mod_log_config 定制日志文件格式 安全考虑 BufferedLogs CookieLog CustomLog LogFormat TransferLog Apache Module mod_log_forensic 定制日志文件格式 安全考虑 ForensicLog Apache Module mod_logio 定制日志文件格式 Apache Module mod_mem_cache MCacheMaxObjectCount MCacheMaxObjectSize MCacheMaxStreamingBuffer MCacheMinObjectSize MCacheRemovalAlgorithm MCacheSize Apache Module mod_mime 带多扩展名的文件 内容编码 字符集和语言 AddCharset AddEncoding AddHandler AddInputFilter AddLanguage AddOutputFilter AddType DefaultLanguage ModMimeUsePathInfo MultiviewsMatch RemoveCharset RemoveEncoding RemoveHandler RemoveInputFilter RemoveLanguage RemoveOutputFilter RemoveType TypesConfig Apache Module mod_mime_magic "Magic文件"的格式 性能问题 注意 MimeMagicFile Apache Module mod_negotiation 类型表 MultiViews CacheNegotiatedDocs ForceLanguagePriority LanguagePriority Apache Module mod_nw_ssl NWSSLTrustedCerts NWSSLUpgradeable SecureListen Apache Module mod_proxy 正向和反向代理 简单示例 控制对代理服务器的访问 缓慢启动 局域网代理 协议调整 请求体 AllowCONNECT NoProxy <Proxy> ProxyBadHeader ProxyBlock ProxyDomain ProxyErrorOverride ProxyIOBufferSize <ProxyMatch> ProxyMaxForwards ProxyPass ProxyPassReverse ProxyPassReverseCookieDomain ProxyPassReverseCookiePath ProxyPreserveHost ProxyReceiveBufferSize ProxyRemote ProxyRemoteMatch ProxyRequests ProxyTimeout ProxyVia Apache Module mod_proxy_ajp Overview of the protocol Basic Packet Structure Request Packet Structure Response Packet Structure Apache Module mod_proxy_balancer Load balancer scheduler algorithm Request Counting Algorithm Weighted Traffic Counting Algorithm Enabling Balancer Manager Support Apache Module mod_proxy_connect Apache Module mod_proxy_ftp 为什么xxx类型的文件不能从FTP下载? 如何强制文件xxx使用FTP的ASCII形式下载? 我如何使用FTP上传? 我如何能访问我自己home目录以外的FTP文件? 我如何才能在浏览器的URL框中隐藏FTP的明文密码? Apache Module mod_proxy_http Apache Module mod_rewrite 特殊字符的引用 环境变量 实用方案 RewriteBase RewriteCond RewriteEngine RewriteLock RewriteLog RewriteLogLevel RewriteMap RewriteOptions RewriteRule Apache Module mod_setenvif BrowserMatch BrowserMatchNoCase SetEnvIf SetEnvIfNoCase Apache Module mod_so 为Windows创建可加载模块 LoadFile LoadModule Apache Module mod_speling CheckSpelling Apache Module mod_ssl 环境变量 Custom Log Formats SSLCACertificateFile SSLCACertificatePath SSLCADNRequestFile SSLCADNRequestPath SSLCARevocationFile SSLCARevocationPath SSLCertificateChainFile SSLCertificateFile SSLCertificateKeyFile SSLCipherSuite SSLCryptoDevice SSLEngine SSLHonorCipherOrder SSLMutex SSLOptions SSLPassPhraseDialog SSLProtocol SSLProxyCACertificateFile SSLProxyCACertificatePath SSLProxyCARevocationFile SSLProxyCARevocationPath SSLProxyCipherSuite SSLProxyEngine SSLProxyMachineCertificateFile SSLProxyMachineCertificatePath SSLProxyProtocol SSLProxyVerify SSLProxyVerifyDepth SSLRandomSeed SSLRequire SSLRequireSSL SSLSessionCache SSLSessionCacheTimeout SSLUserName SSLVerifyClient SSLVerifyDepth Apache Module mod_status Enabling Status Support 自动更新 Machine Readable Status File ExtendedStatus Apache Module mod_suexec SuexecUserGroup Apache Module mod_unique_id Theory Apache Module mod_userdir UserDir Apache Module mod_usertrack Logging 2-digit or 4-digit dates for cookies? CookieDomain CookieExpires CookieName CookieStyle CookieTracking Apache Module mod_version <IfVersion> Apache Module mod_vhost_alias 目录名称的转换 示例 VirtualDocumentRoot VirtualDocumentRootIP VirtualScriptAlias VirtualScriptAliasIP 开发者文档 Overview Topics External Resources Apache API notes Basic concepts How handlers work Resource allocation and resource pools Configuration Debugging Memory Allocation in APR Available debugging options Allowable Combinations Activating Debugging Options Documenting Apache 2.0 Apache 2.0 Hook Functions Creating a hook function Hooking the hook Converting Modules from Apache 1.3 to Apache 2.0 The easier changes ... The messier changes... Request Processing in Apache 2.0 The Request Processing Cycle The Request Parsing Phase The Security Phase The Preparation Phase The Handler Phase How Filters Work in Apache 2.0 Filter Types How are filters inserted? Asis Explanations 词汇和索引 词汇表 模块索引 指令索引 指令速查 译者声明
文字

CGI动态页面

简介

CGI(公共网关接口)定义了web服务器与外部内容生成程序之间交互的方法,通常是指CGI程序或者CGI脚本,它是在网站上实现动态页面的最简单和常用的方法。本文将对如何在Apache web服务器上建立CGI以及如何编写CGI程序进行介绍。

配置Apache以允许CGI

要让CGI程序能正常运作,必须配置Apache以允许CGI的执行,其方法有多种。

ScriptAlias

ScriptAlias指令使Apache允许执行一个特定目录中的CGI程序。当客户端请求此特定目录中的资源时,Apache假定其中所有的文件都是CGI程序并试图运行它。

ScriptAlias指令形如:

ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/

如果Apache被安装到默认位置,默认的配置文件httpd.conf中就会有上述配置。ScriptAliasAlias指令非常相似,都是定义了映射到一个特定目录的URL前缀,两者一般都用于指定位于DocumentRoot以外的目录,其不同之处是ScriptAlias又多了一层含义,即URL前缀后面的任何文件都被视为CGI程序。所以,上述例子会指示Apache:任何以/cgi-bin/开头的资源都将映射到/usr/local/apache2/cgi-bin/目录中,且视之为CGI程序。

例如,如果有URL为http://www.example.com/cgi-bin/test.pl的请求,Apache会试图执行/usr/local/apache2/cgi-bin/test.pl文件并返回其输出。当然,这个文件必须存在而且可执行,并以特定的方法产生输出,否则Apache返回一个出错消息。

ScriptAlias目录以外的CGI

由于安全原因,CGI程序通常被限制在ScriptAlias指定的目录中,这样,管理员就可以严格控制谁可以使用CGI程序。但是,如果采取了恰当的安全措施,则没有理由不允许其他目录中的CGI程序运行。比如,你可能希望用户在UserDir指定的宿主目录中存放页面,而他们有自己的CGI程序,但无权访问cgi-bin目录,这样,就产生了运行其他目录中CGI程序的需求。

允许CGI在任意目录执行需要两个步骤:第一步,必须用AddHandlerSetHandler指令激活cgi-script处理器。第二步,必须在Options指令中启用ExecCGI选项。

用Options显式地允许CGI的执行

可以在主配置文件中,使用Options指令显式地允许特定目录中CGI的执行:

<Directory /usr/local/apache2/htdocs/somedir>
Options +ExecCGI
</Directory>

上述指令使Apache允许CGI文件的执行。另外,还必须告诉服务器哪些文件是CGI文件。下面的AddHandler指令告诉服务器所有带有cgipl后缀的文件是CGI程序:

AddHandler cgi-script .cgi .pl

.htaccess文件

.htaccess指南示范了怎样在没有权限修改httpd.conf文件的情况下激活CGI程序。

用户目录

为了允许用户目录中所有以".cgi"结尾的文件作为CGI程序执行,你可以使用以下配置:

<Directory /home/*/public_html>
Options +ExecCGI
AddHandler cgi-script .cgi
</Directory>

如果你想在用户目录中指定一个cgi-bin子目录,其中所有的文件都被当作CGI程序,你可以这样配置:

<Directory /home/*/public_html/cgi-bin>
Options ExecCGI
SetHandler cgi-script
</Directory>

编写CGI程序

编写CGI程序和"常规"程序之间有两个主要的不同。

首先,在CGI程序的所有输出前面必须有一个HTTP的MIME类型的头,对客户端指明所接收内容的类型,大多数情况下,像这样:

Content-type: text/html

其次,输出要求是HTML形式的,或者是浏览器可以显示的其他某种形式。多数情况下,输出是HTML形式的,但偶然也会输出一个gif图片或者其他非HTML的内容。

除了这两点,编写CGI程序和编写其他程序大致相同。

第一个CGI程序

这个CGI程序的例子在浏览器中打印一行文字。把下列存为first.pl文件,并放在你的cgi-bin目录中。

#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello, World.";

即使不熟悉Perl语言,你也应该能看出它干了什么。第一行,告诉Apache这个文件可以用/usr/bin/perl(或者任何你正在使用的shell)解释并执行。第二行,打印上述要求的内容类型说明,并带有两个换行,在头后面留出空行,以示HTTP头的结束。第三行,打印文字"Hello, World."。程序到此结束。

打开你喜欢的浏览器并输入地址:

http://www.example.com/cgi-bin/first.pl

或者是你存放程序的其他位置,就可以在浏览器窗口中看到一行:Hello, World. 。虽然并不怎么激动人心,但是一旦这个程序能正常运行,那么就可能运行其他任何程序。

程序还是不能运行!

使用浏览器从网络访问CGI程序,可能会发生四种情况:

CGI程序的输出
太好了!这说明一切正常。如果输出正常但是浏览器处理出错,请确认你在CGI程序中使用了正确的 Content-Type
CGI程序的源代码或者一个"POST Method Not Allowed"消息
这说明Apache没有被正确配置以执行CGI程序,重新阅读配置Apache看看遗漏了什么。
一个以"Forbidden"开头的消息
这说明有权限问题。参考Apache错误日志和下面的文件权限。
一个"Internal Server Error"消息
查阅Apache错误日志,可以找到CGI程序产生的出错消息"Premature end of script headers"。对此,需要检查下列各项,以找出不能产生正确HTTP头的原因。

文件的权限

记住,服务器不是以你的用户身份运行的,在服务器启动后,拥有的是一个非特权用户的权限(通常是nobodywww)而需要更大的权限以允许文件的执行。通常,给予nobody足够的权限以执行文件的方法是,对文件赋予任何人皆可执行的权限:

chmod a+x first.pl

另外,如果需要对其他文件进行读取或写入,也必须对这些文件赋予正确的权限。

路径信息和环境变量

当你在命令行执行一个程序,某些信息会自动传给shell而无须你操心,比如PATH ,告诉shell你所引用的文件可以在哪儿找到。

但是,在CGI程序通过web服务器执行时,则没有此PATH ,所以,你在CGI程序中引用的任何程序(如sendmail)都必须指定其完整的路径,使shell能找到它们以执行你的CGI程序。

一种普通的用法是,在CGI程序的第一行中指明解释器(通常是perl),形如:

#!/usr/bin/perl

必须保证它的确指向解释器。

另外,如果CGI程序依赖于某些环境变量,你要确保所需要的变量已经正确的由Apache进行了传递。

程序错误

多数CGI程序失败的原因在于程序本身有问题,尤其是在已经消除上述两种错误而CGI挂起的情况下。在用浏览器测试以前,先在命令行中执行你的程序,能够发现大多数的问题。比如:

cd /usr/local/apache2/cgi-bin
./first.pl

(不要调用perl解释程序,因为shell和Apache会根据脚本第一行的路径信息找到解释器)

你最先看到的输出内容应当是一组HTTP头,包括Content-Type和结尾的空行。如果你看到了别的什么东西,那么当你在服务器上试运行时,Apache会返回 Premature end of script headers 错误。参见上面的编写CGI程序以获得更多信息。

错误日志

错误日志是你的朋友。任何错误都会在错误日志中有所记载,所以你应该首先查看它。如果你的网站空间提供者不允许访问错误日志,那么你应该考虑换一个空间提供者。学会阅读错误日志,可以快速找出问题并快速解决。

Suexec

suexec允许CGI程序根据其所在虚拟主机或用户宿主目录的不同而以不同的用户权限运行。suexec有极其严格的权限校验,任何校验失败都会使CGI程序遭遇 Premature end of script headers 错误。

为了检查你是否使用了suexec ,运行 apachectl -V 并检查SUEXEC_BIN的位置。如果Apache在启动时发现suexec二进制文件正存在于此,那么suexec将会被激活。

除非你很精通suexec,否则请不要使用它。要禁用它,只要删除(或重命名)SUEXEC_BIN所指定位置的suexec二进制文件并重启服务器就可以了。如果你又想启用它,请首先阅读suexec文档以详细了解其运行机制,然后运行 suexec -V 命令找到suexec日志文件,并使用该日志文件找到你违反了哪条判断规则。

幕后是怎样操作的?

当你的CGI编程逐渐深入,理解幕后的操作(尤其是浏览器和服务器之间是如何通讯的)就变得很有用了。因为虽然成功地写了一个程序打印"Hello, World",但并没有实际的用处。

环境变量

环境变量是使用计算机时到处都会用到的变量,比如路径(对实际文件的一个搜索路径以补全你的输入)、你的用户名以及你的终端类型等等。在命令行输入 env ,可以得到当天标准的环境变量列表。

在CGI处理过程中,服务器和浏览器都会设置环境变量,比如浏览器类型(Netscape、IE、Lynx)、服务器类型(Apache、IIS、WebSite)以及将要执行的CGI程序名称等等。

所有这些变量对CGI程序员都有效,但只是客户端-服务器通讯的一半内容。完整的变量列表参见http://hoohoo.ncsa.uiuc.edu/cgi/env.html

这个简单的CGI程序列出了所有的环境变量,Apache发行版的cgi-bin目录中还有一个类似的程序。注意,有些变量是必须的,有些则是可选的,所以你可能会看见一些官方列表中没有的变量。另外,Apache有多种方法可以在默认提供的变量之外增加你的专用环境变量。

#!/usr/bin/perl
print "Content-type: text/html\n\n";
foreach $key (keys %ENV) {
print "$key --> $ENV{$key}<br>";
}

STDIN 和 STDOUT

服务器和客户端之间的其他通讯都通过标准输入设备(STDIN)和标准输出设备(STDOUT)完成。通常,STDIN是指键盘或者一个程序所作用的一个文件,STDOUT指控制台或显示器。

当你POST一个网络表格到一个CGI程序时,表格中的数据被捆扎为一个特殊形式通过STDIN传送给CGI程序,这样,这个程序就可以处理这些数据,仿佛这些数据是来自键盘或者一个文件。

这种"特殊形式"很简单,一个字段名称及其值,中间用等号(=)连接,多个这样的字段对用与符号(&)连接。非常规字符,如空格、"&"号和"="号,被转换为其等值的十六进制以免出问题。整个字符串形如:

name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey

有时,你会发现URL后面也会带有这样的字符串。这种形式会使服务器以这个字符串的内容设置环境变量QUERY_STRING ,称为GET请求。你的HTML表格在FORM标签中设置METHOD属性,以指定传送数据的动作使用GETPOST

你的程序必须把这个字符串分解以获得有用信息。所幸,有库和模块可以帮助你处理这些数据,还有为你的CGI程序达成其他目的的处理器。

CGI模块/库

编写CGI程序时,你应该考虑使用代码库或模块来完成大多数琐碎的工作,以减少错误并更快地开发。

如果用Perl语言编写CGI程序,可用的模块见CPAN ,最常用的模块是CGI.pm 。也可以考虑用CGI::Lite ,它实现了一个在多数程序中所有必须的最小功能集。

如果用C语言编写CGI程序,则有很多选择,其中之一是CGIC库,来自http://www.boutell.com/cgic/

更多信息

网上有大量的CGI资源。可以在Usenet组comp.infosystems.www.authoring.cgi和别人讨论CGI相关问题。HTML Writers Guild 的邮件列表是一个优秀的问题解答资源。更多资源在http://www.hwg.org/lists/hwg-servers/

另外,还可以阅读CGI规范,其中有CGI程序操作的所有细节,原始版本见NCSA ,另有一个更新草案见Common Gateway Interface RFC project

当你向一个邮件列表或者新闻组提交CGI相关问题时,你应该确保提供了足够的信息以更容易地发现并解决问题,诸如:发生了什么事、你希望得到什么结果、结果与你所期望的有什么出入、你运行的服务器、CGI程序是用什么语言编写的、如果可能就提供那个讨厌的代码。

注意,不要把CGI相关问题提交到Apache bug数据库,除非你坚信发现的是Apache源代码中的问题。

上一篇: 下一篇: