温馨提示×

apache在centos如何配置

小樊
39
2026-09-15 01:41:53
栏目: 智能运维

下面按常见场景给你一个在 CentOS(7/8/Stream) 上配置 Apache(httpd) 的实用指南,从安装到常见配置。


一、安装 Apache

CentOS 7

yum install -y httpd

CentOS 8 / Stream

dnf install -y httpd

二、启动与开机自启

systemctl start httpd
systemctl enable httpd

查看状态:

systemctl status httpd

三、防火墙配置(重要)

开放 80 / 443 端口

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

四、测试 Apache 是否正常运行

浏览器访问:

http://服务器IP

看到 Apache Test Page 即成功。


五、网站目录结构

默认网站根目录

/var/www/html

示例:

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

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

1. 创建网站目录

mkdir -p /var/www/example.com/public_html

2. 创建虚拟主机配置文件

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

内容示例:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog /var/log/httpd/example.com-error.log
    CustomLog /var/log/httpd/example.com-access.log combined
</VirtualHost>

3. 重启 Apache

systemctl restart httpd

七、常见配置修改

1. 修改默认端口(如 8080)

编辑:

vi /etc/httpd/conf/httpd.conf

修改:

Listen 8080

重启:

systemctl restart httpd

2. 允许 .htaccess

<Directory "/var/www/html">
    AllowOverride All
</Directory>

3. 开启目录列表(不推荐生产环境)

Options +Indexes

八、HTTPS(SSL)配置(可选)

安装模块

yum install -y mod_ssl

自签证书示例

openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/pki/tls/private/apache.key \
-out /etc/pki/tls/certs/apache.crt

配置 SSL

vi /etc/httpd/conf.d/ssl.conf

九、日志位置

  • 访问日志:/var/log/httpd/access_log
  • 错误日志:/var/log/httpd/error_log

十、排错建议

journalctl -xe
tail -f /var/log/httpd/error_log
httpd -t   # 检查配置语法

如果你有具体需求(如 PHP 支持、反向代理、多域名、安全加固),可以告诉我,我可以给你更针对性的配置。

0