温馨提示×

如何在CentOS Apache中优化网站速度

小樊
36
2025-11-21 21:50:21
栏目: 云计算

CentOS Apache 网站速度优化实操指南

一 基础网络与连接优化

  • 启用持久连接 KeepAlive,复用 TCP 连接,降低握手开销:
    KeepAlive On
    MaxKeepAliveRequests 100
    KeepAliveTimeout 5
    
  • 调整日志以减少 I/O 压力(保持必要的访问审计时可适度降低级别):
    LogLevel warn
    
  • 可选的系统层面网络优化(/etc/sysctl.conf),提升高并发下的连接处理能力:
    net.ipv4.tcp_fin_timeout = 30
    net.ipv4.tcp_keepalive_time = 1200
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_tw_recycle = 1
    net.ipv4.ip_local_port_range = 1024 65000
    net.ipv4.tcp_max_syn_backlog = 8192
    net.ipv4.tcp_max_tw_buckets = 5000
    # 使配置生效
    sysctl -p
    
    以上设置能减少连接建立/销毁次数、优化端口与半连接队列,对高并发站点尤为有效。

二 启用压缩与静态资源缓存

  • 启用 Gzip 压缩,减小传输体积(优先使用 mod_deflate):
    # 检查模块
    apachectl -M | grep deflate
    
    # 配置示例
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
        # 可选:压缩级别 1-9,9 最高(CPU 更高)
        DeflateCompressionLevel 6
        # 已压缩资源无需再压
        SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|bz2|rar|pdf)$ no-gzip dont-vary
    </IfModule>
    
  • 配置浏览器缓存,利用 mod_expires 设置资源过期时间,减少重复请求:
    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType text/css                  "access plus 30 days"
        ExpiresByType application/javascript  "access plus 30 days"
        ExpiresByType image/jpeg               "access plus 1 year"
        ExpiresByType image/png                "access plus 1 year"
        ExpiresByType image/gif                "access plus 1 year"
        ExpiresByType image/svg+xml            "access plus 1 year"
        ExpiresByType font/woff2               "access plus 1 year"
    </IfModule>
    
  • 如需更细粒度控制,可配合 mod_headers 设置 Cache-Control:
    <IfModule mod_headers.c>
        Header set Cache-Control "public, max-age=31536000" env=!no-cache
    </IfModule>
    
    压缩与缓存是最“低成本、高收益”的优化项,建议优先启用与验证。

三 调整 MPM 并发模型与关键参数

  • 确认并切换合适的 MPM(多处理模块):
    • 查看:httpd -V | grep -i mpm(常见:preforkworkerevent
    • 切换:在 /etc/httpd/conf.modules.d/00-mpm.conf 中启用对应模块(如 LoadModule mpm_event_module modules/mod_mpm_event.so),注释其他 MPM;随后重启 httpd。
  • 典型参数示例(需结合内存与压测微调):
    • prefork(适合传统 PHP 模块场景,非线程安全):
      <IfModule mpm_prefork_module>
          StartServers        5
          MinSpareServers     5
          MaxSpareServers    10
          ServerLimit       256
          MaxRequestWorkers 150   # 依据内存与单进程占用调整
          MaxConnectionsPerChild 10000
      </IfModule>
      
    • event(事件驱动,高并发更优,需 httpd >= 2.4 且模块可用):
      <IfModule mpm_event_module>
          StartServers         2
          MinSpareThreads     25
          MaxSpareThreads     75
          ThreadLimit         64
          ThreadsPerChild     25
          MaxRequestWorkers  400
          MaxConnectionsPerChild 0
      </IfModule>
      
  • 提示:
    • 动态内容(如 mod_php)通常选 prefork;反向代理/静态资源为主可选 event
    • 每次调整务必进行压测与稳定性观察,避免过高并发导致内存耗尽或进程抖动。

四 启用 HTTP/2 与反向代理缓存加速

  • 启用 HTTP/2(需 TLS/SSL):
    # 确认模块
    apachectl -M | grep http2
    
    # 在 SSL VirtualHost 中启用
    Protocols h2 http/1.1
    
    HTTP/2 多路复用可显著改善多资源页面的加载速度。
  • 反向代理与页面缓存(Varnish 前置 + Apache 后端):
    • 架构建议:客户端 → Varnish(端口 80)→ Apache(端口 8080
    • Varnish 示例(/etc/varnish/default.vcl):
      vcl 4.0;
      backend default {
          .host = "127.0.0.1";
          .port = "8080";
      }
      sub vcl_recv {
          if (req.method == "PURGE") {
              return(purge);
          }
          return(hash);
      }
      sub vcl_backend_response {
          set beresp.ttl = 120s;
          unset beresp.http.Set-Cookie;
      }
      
    • Apache 侧将监听改为 8080 并启用压缩/缓存头;Nginx 亦可替代 Varnish 作为反向代理与静态资源服务。
  • 若需 Apache 内置页面级缓存,可启用 mod_cache/mod_cache_disk(适合特定路径或整站边缘缓存):
    <IfModule mod_cache.c>
        <IfModule mod_cache_disk.c>
            CacheEnable disk  /
            CacheRoot "/var/cache/apache2/mod_cache_disk"
            CacheDirLevels 2
            CacheDirLength 1
            CacheDefaultExpire 3600
        </IfModule>
    </IfModule>
    
    HTTP/2 与反向代理/页面缓存适合中高流量站点,能显著降低后端压力与首包时间。

五 验证与持续监控

  • 验证要点:
    • 压缩:浏览器开发者工具或 curl -I 查看响应头 Content-Encoding: gzip
    • HTTP/2:开发者工具 Protocol 列显示 h2
    • 缓存:响应头 Cache-Control / Expires 是否符合预期。
  • 压测与观测:
    • 基准测试:ab -n 10000 -c 200 https://your-site/
    • 实时监控:top, ss -s, tail -f /var/log/httpd/error_log
    • 建议分阶段变更、灰度发布,并保留回滚方案。
  • 配套优化(可选):
    • 启用 CDN 加速静态资源与全站加速。
    • 优化数据库(连接池、索引、慢查询治理),降低后端瓶颈对 Apache 的影响。

0