You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CentOS7下Apache2.4环境CGI Perl脚本无法写入文件求助

CentOS7下Apache2.4 Perl CGI写入文件触发500错误排查解决

问题现象

运行环境:CentOS7 + Apache2.4

  • 带文件写入操作的Perl CGI脚本返回Internal Server Error,错误日志显示:

    [Thu Sep 07 01:07:37.226029 2023] [cgi:error] [pid 28876] [client 2.221.192.244:56475] AH01215: (8)Exec format error: exec of '/home/sle/domains/mydomain.com/public_html/cgi-bin/GzK8PhiWEfM9c4jZgyNrpYb5RtnD3ex6/test.cgi' failed: /home/sle/domains/mydomain.com/public_html/cgi-bin/GzK8PhiWEfM9c4jZgyNrpYb5RtnD3ex6/test.cgi
    [Thu Sep 07 01:07:37.226322 2023] [cgi:error] [pid 28876] [client 2.221.192.244:56475] End of script output before headers: test.cgi

  • 无文件写入操作的CGI脚本可正常运行;调整文件/目录所有者、权限(甚至设为777)、移动文件位置、修改虚拟主机配置均无效。

测试脚本路径:/home/sle/domains/mydomain.com/public_html/cgi-bin/GzK8PhiWEfM9c4jZgyNrpYb5RtnD3ex6/test.cgi

#!/usr/bin/perl
use strict;
use warnings;
use CGI ":standard";

print "Content-type:text/html \n\n";

open (FILE, '>', "/home/sle/domains/mydomain.com/public_html/test.txt") or die ("Could not open the file for writing...$!");
print FILE "something";
close(FILE); 

排查与解决步骤

1. 修复脚本换行符问题

错误日志中的Exec format error常见原因是脚本使用Windows换行符(CRLF),而Linux要求LF换行。

  • 检查换行符:执行cat -A /home/sle/domains/mydomain.com/public_html/cgi-bin/GzK8PhiWEfM9c4jZgyNrpYb5RtnD3ex6/test.cgi,若行尾显示^M$则为CRLF格式。
  • 转换为LF:执行dos2unix /home/sle/domains/mydomain.com/public_html/cgi-bin/GzK8PhiWEfM9c4jZgyNrpYb5RtnD3ex6/test.cgi,之后重启Apache。

2. 修正脚本错误输出逻辑

End of script output before headers是因为当open失败触发die时,错误信息没有先输出HTTP头,导致Apache认为脚本未返回合法响应。修改脚本,确保无论成功失败都先输出HTTP头:

#!/usr/bin/perl
use strict;
use warnings;
use CGI ":standard";

# 先输出HTTP头
print "Content-type:text/html \n\n";

open (FILE, '>', "/home/sle/domains/mydomain.com/public_html/test.txt") or do {
    print "Could not open the file for writing...$!";
    exit;
};
print FILE "something";
close(FILE); 

print "File written successfully!";

3. 检查SELinux限制

CentOS7默认开启SELinux,可能阻止Apache进程写入文件:

  • 临时关闭测试:执行setenforce 0,重新访问脚本,若恢复正常则是SELinux问题。
  • 永久添加规则:执行chcon -R -t httpd_sys_rw_content_t /home/sle/domains/mydomain.com/public_html/,让SELinux允许Apache读写该目录。

4. 调整mod_ruid2组权限

虚拟主机中RGroups @none可能导致sle用户缺少必要的写入权限:

  • 编辑虚拟主机配置,取消注释#RGroups apache access,改为:
    RGroups apache access
    
  • 重启Apache:systemctl restart httpd

5. 验证父目录权限

确保目标文件的父目录权限允许sle用户写入:

  • 检查权限:ls -ld /home/sle/domains/mydomain.com/public_html/,确保权限至少为755,所有者为sle:sle。
  • 若权限不足,执行:chown -R sle:sle /home/sle/domains/mydomain.com/public_html/ && chmod -R 755 /home/sle/domains/mydomain.com/public_html/

内容的提问来源于stack exchange,提问作者SB121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 14:05:26