温馨提示×

centos apache配置哪些步骤

小樊
38
2026-08-29 23:45:49
栏目: 智能运维

下面以 CentOS 7/8 为例,说明 Apache(httpd) 的基础配置步骤,适合新手快速搭建一个可用站点。


一、安装 Apache

CentOS 7

yum install -y httpd

CentOS 8(已停止维护,建议用 dnf)

dnf install -y httpd

二、启动并设置开机自启

systemctl start httpd
systemctl enable httpd

确认状态:

systemctl status httpd

三、防火墙放行 HTTP/HTTPS

开放端口

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

测试端口

curl http://localhost

或浏览器访问服务器 IP。


四、Apache 目录结构说明

目录 / 文件 作用
/etc/httpd/ 主配置目录
/etc/httpd/conf/httpd.conf 主配置文件
/etc/httpd/conf.d/ 自定义配置文件
/var/www/html/ 默认网站根目录
/var/log/httpd/ 日志目录

五、修改默认站点(基础配置)

1️⃣ 修改默认首页

echo "Hello CentOS Apache" > /var/www/html/index.html

访问:

http://服务器IP

六、配置虚拟主机(推荐)

1️⃣ 新建虚拟主机配置文件

vim /etc/httpd/conf.d/example.conf

示例:

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example

    <Directory /var/www/example>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/example_error.log
    CustomLog /var/log/httpd/example_access.log combined
</VirtualHost>

2️⃣ 创建网站目录

mkdir -p /var/www/example
echo "Example Site" > /var/www/example/index.html

3️⃣ 检查配置并重启

httpd -t
systemctl restart httpd

七、绑定域名(可选)

  1. 域名 DNS 解析指向服务器 IP
  2. ServerName 使用真实域名
  3. 重启 Apache

八、开启伪静态(URL Rewrite)

确认模块已加载(默认已加载):

httpd -M | grep rewrite

在目录中开启:

AllowOverride All

九、SELinux 常见处理(很重要)

查看状态

getenforce

临时关闭(测试用)

setenforce 0

正确方式(推荐)

setsebool -P httpd_can_network_connect 1
semanage fcontext -a -t httpd_sys_content_t "/var/www/example(/.*)?"
restorecon -Rv /var/www/example

十、常用命令总结

systemctl start httpd
systemctl stop httpd
systemctl restart httpd
httpd -t
ss -lntp | grep 80

如果你需要:

  • CentOS 7 + PHP
  • HTTPS(Let’s Encrypt)
  • 多站点配置
  • Apache 性能优化

可以告诉我你的具体需求,我可以按实际使用场景一步一步讲。

0