温馨提示×

centos中apache如何配

小樊
45
2026-10-17 14:06:33
栏目: 智能运维

在 CentOS 中配置 Apache(通常叫 httpd)一般包括:安装 → 启动 → 防火墙 → 虚拟主机 → 常见配置。下面按步骤说明(以 CentOS 7/8 为例,CentOS 6 略有差异)。


一、安装 Apache

# CentOS 7/8
sudo yum install httpd -y
# 或 CentOS 8 也可用
sudo dnf install httpd -y

查看版本:

httpd -v

二、启动并设置开机自启

sudo systemctl start httpd
sudo systemctl enable httpd

查看状态:

sudo systemctl status httpd

三、防火墙放行 80/443

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

四、测试访问

浏览器访问:

http://服务器IP

看到 Apache Test Page 即成功。


五、网站目录结构

默认网站根目录:

/var/www/html

默认配置文件:

/etc/httpd/conf/httpd.conf

模块配置目录:

/etc/httpd/conf.d/

六、配置虚拟主机(多网站)

1. 创建网站目录

sudo mkdir -p /var/www/example.com/public_html
sudo chown -R apache:apache /var/www/example.com

2. 创建虚拟主机配置

sudo vi /etc/httpd/conf.d/example.conf

内容示例:

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

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

    ErrorLog /var/log/httpd/example.com-error.log
    CustomLog /var/log/httpd/example.com-access.log combined
</VirtualHost>

3. 重启 Apache

sudo systemctl restart httpd

七、开启 rewrite(伪静态)

在 <Directory> 中确保:

AllowOverride All

启用模块(默认已启用):

sudo httpd -M | grep rewrite

八、配置 HTTPS(可选)

使用 Let’s Encrypt

sudo yum install certbot python3-certbot-apache -y
sudo certbot --apache

九、常用命令

# 检查配置是否正确
sudo apachectl configtest

# 重启
sudo systemctl restart httpd

# 查看错误日志
sudo tail -f /var/log/httpd/error_log

如果你有具体需求(如 PHP 环境、反向代理、多端口、CentOS 版本不同),可以告诉我,我给你对应的配置示例。

0 踩