必须完成apache安装、自定义站点根目录、调整监听端口,并确保服务稳定启停和开机自启;具体包括:yum install httpd -y安装,systemctl enable && start httpd启用并启动,firewall-cmd放行端口,修改documentroot和listen配置,同步更新servername及selinux端口策略,最后systemctl restart生效。

要在CentOS系统上让网站真正跑起来,必须完成Apache的安装、自定义站点根目录、调整监听端口,并确保服务能稳定启停和开机自启,缺一不可。
安装与基础服务管理
执行 yum install httpd -y 安装Apache主程序,该命令会自动解决所有依赖关系。
安装完成后立即启用并启动服务:systemctl enable httpd && systemctl start httpd。这一步必须做,否则重启后服务不会自动运行。
用 systemctl status httpd 查看状态,确认输出中包含 active (running) 且 Main PID 非零,才算真正就绪。
若看到 “failed” 或 “inactive”,先别改配置——90% 是防火墙或 SELinux 拦截所致,跳过此步直接看下一节排障。
开放防火墙端口并验证连通性
CentOS 7 默认启用 firewalld,80 端口默认被封锁。执行以下两条命令永久放行:
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
然后必须执行 firewall-cmd --reload 才能使规则生效,仅 --permanent 不会立刻起作用。
验证是否成功:运行 firewall-cmd --list-services | grep http,输出含 http https 即表示已登记;再用 curl -I http://localhost 检查返回码是否为 200 OK。
如果本地 curl 成功但局域网其他机器无法访问,请检查虚拟机网络模式(需为桥接或NAT+端口转发),不是 Apache 配置问题。
修改默认站点根目录
方法一:直接修改主配置文件
编辑 /etc/httpd/conf/httpd.conf,定位到 DocumentRoot "/var/www/html" 行,将其改为你的目标路径,例如 DocumentRoot "/srv/myweb"。
紧接着找到对应的 <directory></directory> 块,把路径同步改成 <directory></directory>,否则会因权限拒绝导致 403 错误。
方法二:使用 conf.d 下的独立配置(推荐)
新建文件 /etc/httpd/conf.d/site-root.conf,写入:
DocumentRoot "/srv/myweb"
<directory></directory>
Require all granted
PHP中文网提供Apache 2.4.62 官方 tar.gz 源码包下载,通过源码编译安装,开发者能够灵活定制模块、优化性能并精准控制安装路径,满足多样化的业务需求。
这样既避免污染主配置,又便于多站点隔离。注意:新目录需存在且属主为 apache:apache,执行 chown -R apache:apache /srv/myweb。
更改Apache监听端口
第一步:修改主配置中的 Listen 指令
打开 /etc/httpd/conf/httpd.conf,找到 Listen 80 这一行,改为例如 Listen 8080。
第二步:同步更新 ServerName(关键!)
查找 #ServerName www.example.com:80,取消注释并在其后添加新端口:ServerName localhost:8080。不加端口会导致重定向异常或模块加载失败。
第三步:SELinux 端口策略适配(仅当启用 SELinux 时必需)
运行 semanage port -l | grep http_port_t 查看当前允许的 HTTP 类型端口列表。若 8080 不在其中,执行:semanage port -a -t http_port_t -p tcp 8080。
第四步:开放防火墙新端口
执行 firewall-cmd --permanent --add-port=8080/tcp → firewall-cmd --reload。
最后重启服务:systemctl restart httpd。若报错 Permission denied: make_sock: could not bind to address,说明 SELinux 策略未生效或端口已被占用。
常用服务控制命令速查
启动服务:systemctl start httpd
停止服务:systemctl stop httpd
重启服务(完全重载):systemctl restart httpd
重载配置(不中断连接):systemctl reload httpd
查看当前状态:systemctl status httpd
设置开机自启:systemctl enable httpd
禁用开机自启:systemctl disable httpd
检查是否已启用自启:systemctl is-enabled httpd(返回 enabled 表示成功)










