解决 Apache 报错 Script timed out before returning headers 的排查指南
排查与解决 Apache 调用 CGI/FastCGI/WSGI 脚本超时提示 Script timed out before returning headers 的完整方案。
问题现象
在浏览器中运行复杂统计分析、大文件处理或数据导出时,页面卡死并最终呈现 500 Internal Server Error。查看 Apache 错误日志记录:
[cgid:error] [pid 1234:tid 5678] [client 10.0.1.20:54321] AH01215: cgi-bin/export.py: Script timed out before returning headers: export.py
或者在 FastCGI 模块下提示 mod_fcgid: read data timeout in 40 seconds。
触发根因
- 调用的外部脚本(Python WSGI/CGI、Perl、PHP)在执行过程中遭遇数据库慢查询、锁等待死锁或第三方 API 阻塞,未能在超时时限内输出标准 HTTP 响应头。
- Apache 的
Timeout全局指令(默认通常为 60 秒)或mod_cgid/mod_fcgid的超时参数设置过于严苛。
解决步骤与操作命令
步骤一:针对 mod_cgid / mod_fcgid 调大脚本执行超时
编辑 Apache 配置文件(如 /etc/apache2/mods-available/fcgid.conf 或全局配置):
# 调大全局请求超时为 300 秒(5 分钟)
Timeout 300
<IfModule mod_fcgid.c>
# 调大 FastCGI 响应超时
FcgidIOTimeout 300
FcgidConnectTimeout 60
FcgidBusyTimeout 300
</IfModule>
<IfModule mod_cgid.c>
# 调大标准 CGI 脚本超时
CGIDScriptTimeout 300
</IfModule>
步骤二:优化脚本内部的慢调用逻辑
使用性能剖析工具定位脚本耗时瓶颈:
- 检查数据库 SQL 查询是否命中索引。
- 为调用的外部 HTTP API 设置严格的连接与读取超时保护(如
requests.get(url, timeout=10))。
步骤三:重载 Apache 服务配置
sudo apachectl configtest
sudo systemctl reload apache2 # 在 CentOS 上为 httpd
验证确认
再次发起耗时导出任务请求: 页面在持续计算 90 秒后成功返回生成的文件流,Apache 错误日志中未再产生任何 Script timed out 报错。


