首先确认Apache服务是否正在运行,若未启动则无法响应请求。使用以下命令检查服务状态:
sudo systemctl status httpd 若服务未启动,执行以下命令启动:
sudo systemctl start httpd 并设置开机自启:
sudo systemctl enable httpd 错误日志是定位404问题的关键,Apache的默认错误日志路径为/var/log/httpd/error_log。使用以下命令实时查看最新错误信息:
sudo tail -f /var/log/httpd/error_log 日志中会明确提示“File does not exist”(文件不存在)或“Directory index forbidden”(目录索引被禁止)等具体原因,帮助快速定位问题。
404错误最常见的原因是请求的文件或目录不存在。需检查:
/etc/httpd/conf/httpd.conf)或虚拟主机配置文件(/etc/httpd/conf.d/*.conf),确认DocumentRoot指令指向的路径正确(如/var/www/html)。ls命令检查请求的文件是否在DocumentRoot目录下,例如:ls -l /var/www/html/index.html DirectoryIndex指令包含默认索引文件(如index.html、index.php),避免因缺少索引文件导致404。Apache进程(通常为apache或www-data用户)需具备读取和执行权限才能访问文件和目录。执行以下命令调整权限:
# 将网站根目录所有者设为apache用户 sudo chown -R apache:apache /var/www/html # 设置目录权限为755(所有者可读/写/执行,其他用户可读/执行) sudo chmod -R 755 /var/www/html # 设置文件权限为644(所有者可读/写,其他用户可读) sudo find /var/www/html -type f -exec chmod 644 {} \; 注意:避免将权限设置为777(完全开放),以免引发安全问题。
若系统启用了SELinux(默认开启),可能会阻止Apache访问非标准目录或文件。执行以下命令检查SELinux状态:
getenforce Enforcing(启用),可临时禁用测试是否为SELinux导致的问题:sudo setenforce 0 # 允许Apache访问网站根目录 sudo chcon -R -t httpd_sys_content_t /var/www/html # 若需写入权限(如上传文件),添加以下命令 sudo chcon -R -t httpd_sys_rw_content_t /var/www/html/upload_dir 注意:禁用SELinux会降低系统安全性,建议仅在测试环境使用。若使用虚拟主机,需检查虚拟主机配置文件(/etc/httpd/conf.d/*.conf)中的DocumentRoot指令是否正确,且<Directory>块中包含Require all granted(允许访问):
<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html/example.com <Directory /var/www/html/example.com> AllowOverride All Require all granted </Directory> </VirtualHost> 修改配置后,使用以下命令检查语法并重启Apache:
sudo apachectl configtest sudo systemctl restart httpd 若网站根目录下存在.htaccess文件,可能包含URL重写规则(如mod_rewrite)导致404。需确认:
mod_rewrite模块已启用:sudo a2enmod rewrite # CentOS中通常无需此命令,默认启用 .htaccess文件配置正确,尤其是RewriteBase和RewriteRule指令。.htaccess覆盖设置(AllowOverride All)。确保防火墙允许HTTP(端口80)和HTTPS(端口443)流量,否则客户端无法访问服务器。执行以下命令开放端口:
# 开放HTTP和HTTPS端口 sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https # 重新加载防火墙规则 sudo firewall-cmd --reload 检查端口是否开放:
sudo firewall-cmd --list-all 应包含http和https服务。