温馨提示×

CentOS Apache配置指南

小樊
39
2025-12-17 13:02:58
栏目: 智能运维

CentOS Apache 配置指南

一 环境准备与安装

  • 更新系统并安装 Apache(httpd):
    • 命令:sudo yum update -ysudo yum install httpd -y
  • 启动并设置开机自启:
    • 命令:sudo systemctl start httpdsudo systemctl enable httpd
  • 防火墙放行 HTTP/HTTPS:
    • 命令:sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=httpssudo firewall-cmd --reload
  • 验证安装:
    • 访问 http://服务器IP或域名,出现 Apache 测试页即成功。

二 基础配置与目录结构

  • 主配置文件与包含路径:
    • 主配置:/etc/httpd/conf/httpd.conf
    • 额外配置:在 /etc/httpd/conf.d/ 下以 .conf 结尾的文件会被自动包含,适合按站点拆分配置。
  • 默认文档根目录与测试页:
    • 目录:/var/www/html
    • 快速测试:echo "<h1>Hello from Apache on CentOS</h1>" | sudo tee /var/www/html/index.html
  • 常用运维命令:
    • 语法检查:sudo apachectl configtest
    • 热重载:sudo systemctl reload httpd
    • 重启:sudo systemctl restart httpd
    • 查看状态:sudo systemctl status httpd

三 虚拟主机配置

  • 基于名称的虚拟主机(推荐):
    • 创建目录与权限:
      • sudo mkdir -p /var/www/example.com
      • sudo chown -R apache:apache /var/www/example.com
      • sudo chmod -R 755 /var/www/example.com
    • 站点配置(/etc/httpd/conf.d/example.com.conf):
      <VirtualHost *:80>
          ServerAdmin admin@example.com
          DocumentRoot /var/www/example.com
          ServerName example.com
          ServerAlias www.example.com
          ErrorLog /var/log/httpd/example.com-error.log
          CustomLog /var/log/httpd/example.com-access.log combined
      </VirtualHost>
      
    • 使配置生效:sudo systemctl reload httpd
  • 本地测试(域名尚未解析时):
    • 在测试机编辑 /etc/hosts服务器IP example.com www.example.com
    • 使用 curl http://example.com 验证。

四 启用 HTTPS 与自动续期

  • 安装 Certbot 并获取证书:
    • 安装 EPEL 与插件:sudo yum install epel-release -ysudo yum install certbot python2-certbot-apache -y
    • 申请并自动配置 HTTPS:sudo certbot --apache -d example.com -d www.example.com
  • 自动续期:
    • 添加定时任务:sudo crontab -e
    • 示例(每日检查):0 0 * * * /usr/bin/certbot renew --quiet

五 安全与性能优化

  • SELinux 与文件上下文:
    • 为网站目录设置正确上下文(示例):sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?"
    • 应用上下文:sudo restorecon -Rv /var/www/example.com
  • 安全加固建议:
    • 隐藏版本信息:ServerTokens ProdServerSignature Off
    • 按需加载模块,禁用不必要模块,减少攻击面。
  • 性能优化要点:
    • 启用长连接与压缩:
      KeepAlive On
      MaxKeepAliveRequests 100
      KeepAliveTimeout 5
      
      <IfModule mod_deflate.c>
          AddOutputFilterByType DEFLATE text/html text/css application/javascript
      </IfModule>
      
    • 缓存模块(可选):sudo yum install mod_cache mod_cache_disk -y,并按需配置磁盘缓存。
    • MPM 选择与调优:
      • 查看 MPM:httpd -V
      • 常见选择:event(高并发、Keep-Alive 友好)、workerprefork(与线程不安全的模块/旧版 PHP 更兼容)
      • 在对应 MPM 配置段调整如 MaxRequestWorkersStartServers 等参数,避免资源争用与排队。

0