Windows Apache 配置 CGI 模式运行 Python 脚本
本文介绍在 Windows 系统中配置 Apache 以 CGI 模式运行 Python 脚本的方法。通过修改 httpd.conf 中的 ScriptInterpreterSource、Options 及 AddHandler 指令,实现 .py 文件的执行。文中包含测试代码示例及常见错误(如 500、403 错误)的排查与解决建议,对比了 CGI 与 mod_python 的性能差异。
配置背景与方案选择
由于系统中已安装 Python 2.6 及支持该版本的 Eric4 编辑器,为避免重新安装 Python 2.5 来配置 Apache 下的 mod_python,决定采用其他方案。
随后发现一篇名为 Running Python as CGI in Apache in Windows 的文章,介绍了以 CGI 模式替代 mod_python 来运行 Python 脚本的方法。此外,Python for Windows 也是一份参考资源。
具体操作步骤如下:
Apache 配置步骤详解
首先打开 httpd.conf 配置文件,定位到“#ScriptInterpreterSource Registry”这一行,移除其前缀的注释符号 #(若未找到该行,则手动添加)。接着找到“Options Indexes FollowSymLinks”,在其后追加“ExecCGI”。建议同时移除“Indexes”参数,因为若保留该参数且目录下缺少 index.html 等索引文件,Apache 将列出目录中所有文件,存在安全隐患;移除后若无索引文件,则返回 Forbidden 页面。随后定位“AddHandler cgi-script .cgi”,在其后追加“.py”;若该行不存在,需手动添加“AddHandler cgi-script .py”。完成配置后重启 Apache(若 restart 导致服务无响应,可尝试先 stop 再 start)。
测试脚本与运行验证
创建一个 test.py 脚本,内容如下: print "Content-type: text/html" print "" print "<html><head></head><body>" print "Hello World" print "</body></html>" 注意第二句 print “”不可省略,否则会导致“500 Internal Server Error”错误。
在浏览器中访问 http://localhost/test.py,若页面输出“Hello World”,则表明运行正常。
此外,可能遇到以下错误提示:
常见错误排查与原理说明
若未添加 ScriptInterpreterSource Registry,会触发 500 Internal Server Error 错误。若未添加 ExecCGI,会返回 403 Forbidden You don't have permission to access /test.py on this server。若未添加 AddHandler cgi-script .py,浏览器将以纯文本形式显示脚本内容。
注:添加 ScriptInterpreterSource Registry 的目的是让 Windows 通过注册表定位 Python 的安装路径。添加 ExecCGI 允许 Python 脚本在任意目录下运行,因为 Apache 默认仅允许在 cgi-bin 目录下执行 CGI 脚本;若将 test.py 置于 htdocs 下而未加此配置,会报 403 Forbidden 错误。启用 ExecCGI 虽方便但存在安全风险,使用 FastCGI 更为安全,但需预先安装 FastCGI。CGI 模式的执行速度通常慢于 mod_python 模式,因此未来可在其他电脑上尝试 mod_python 模式。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









