温馨提示×

怎样通过Apache2提升页面加载速度

小樊
31
2025-12-20 23:33:50
栏目: 编程语言

Apache2 页面加载速度优化实操指南

一 核心优化清单

  • 启用压缩:使用 mod_deflate 对文本资源进行 Gzip 压缩,显著降低传输体积。
  • 浏览器缓存:使用 mod_expires 设置 Cache-Control/Expires,让浏览器长期缓存静态资源。
  • 连接复用:开启 KeepAlive 减少 TCP/TLS 握手与慢启动带来的开销。
  • 多路复用:启用 HTTP/2(建议 Apache ≥ 2.4.5),提升并发与首包时间。
  • 传输安全与性能:启用 TLS 并优化 OCSP Stapling、会话缓存。
  • 服务器端缓存:按需启用 mod_cache/mod_cache_disk 做反向代理或页面级缓存。
  • 并发与进程模型:选择并调优 MPM(event/worker/prefork) 以匹配 CPU/内存与并发。
  • 资源瘦身:压缩图片(如 WebP/AVIF)、精简与合并 CSS/JS、接入 CDN
  • 模块管理:禁用不需要的模块,降低内存与 CPU 占用。

二 关键配置示例

  • 启用压缩(mod_deflate)

    • Debian/Ubuntu
      sudo a2enmod deflate
      
    • 配置片段(建议写入 /etc/apache2/mods-enabled/deflate.conf 或站点配置)
      <IfModule mod_deflate.c>
          AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
          # 可选:压缩级别 Apache ≥ 2.4.25
          DeflateCompressionLevel 6
          # 可选:对已是压缩格式的资源跳过压缩
          SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|bz2)$ no-gzip dont-vary
      </IfModule>
      
    • 验证:响应头出现 Content-Encoding: gzip
  • 浏览器缓存(mod_expires)

    sudo a2enmod expires
    
    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType image/jpg  "access plus 1 year"
        ExpiresByType image/jpeg "access plus 1 year"
        ExpiresByType image/gif  "access plus 1 year"
        ExpiresByType image/png  "access plus 1 year"
        ExpiresByType text/css  "access plus 1 month"
        ExpiresByType application/javascript "access plus 1 month"
        ExpiresByType application/x-javascript "access plus 1 month"
        ExpiresDefault "access plus 2 days"
    </IfModule>
    
    • 验证:响应头出现 Cache-Control: max-age=Expires
  • KeepAlive 复用

    KeepAlive On
    MaxKeepAliveRequests 100
    KeepAliveTimeout 5
    
    • 建议:高并发短连接场景可适当提高 MaxKeepAliveRequests;移动网络可适当降低 KeepAliveTimeout
  • HTTP/2(需 Apache ≥ 2.4.5 且启用 TLS)

    sudo a2enmod http2
    
    • 在 <VirtualHost *:443> 中加入:
      Protocols h2 http/1.1
      
    • 验证:Chrome 开发者工具 Protocol 列显示 h2
  • TLS 与 OCSP Stapling

    SSLEngine on
    SSLCertificateFile    /path/to/fullchain.pem
    SSLCertificateKeyFile /path/to/privkey.pem
    
    # 生成 DH 参数(一次即可)
    # openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
    
    SSLOpenSSLConfCmd DHParameters "/etc/ssl/certs/dhparam.pem"
    SSLUseStapling On
    SSLStaplingCache "shmcb:/var/run/stapling-cache(150000)"
    
    SSLSessionCache "shmcb:/var/run/ssl_scache(512000)"
    SSLSessionCacheTimeout 300
    
    • 验证:访问站点,检查 OCSP Stapling: yes(如 testssl.sh/浏览器)。
  • 服务器端缓存(mod_cache_disk,按需)

    sudo a2enmod cache
    sudo a2enmod cache_disk
    
    <IfModule mod_cache.c>
        <IfModule mod_cache_disk.c>
            CacheRoot "/var/cache/apache2/mod_cache_disk"
            CacheEnable disk /
            CacheDirLevels 2
            CacheDirLength 1
            CacheDefaultExpire 3600
            CacheMaxExpire 86400
            CacheIgnoreHeaders Set-Cookie
            CacheIgnoreNoLastMod On
        </IfModule>
    </IfModule>
    
    • 提示:对动态内容启用需谨慎,建议先对静态资源或命中率高的页面做 A/B 验证。
  • MPM 选择与调优(以 event 为例,路径因发行版而异)

    • 查看与切换(Debian/Ubuntu)
      sudo a2enmod mpm_event
      sudo a2dismod mpm_prefork mpm_worker   # 视当前启用情况调整
      
    • 示例参数(需结合内存/CPU/并发实测微调)
      <IfModule mpm_event_module>
          StartServers             2
          MinSpareThreads         25
          MaxSpareThreads         75
          ThreadLimit             64
          ThreadsPerChild         25
          MaxRequestWorkers       150
          MaxConnectionsPerChild   0
      </IfModule>
      
    • 原则:event 适合高并发短连接;prefork 适合阻塞型应用(如部分 mod_php)。

三 验证与上线步骤

  • 配置语法检查
    sudo apache2ctl configtest
    
  • 优雅重启
    sudo systemctl reload apache2    # 或 restart
    
  • 验证要点
    • 压缩:响应头 Content-Encoding: gzip
    • 缓存:响应头 Cache-Control: max-age=Expires
    • HTTP/2:开发者工具 Protocol=h2
    • OCSP Stapling:工具或浏览器显示已启用。
    • 性能对比:使用 Lighthouse/GTmetrixcurl -w 对比 TTFB/首屏/总耗时

四 进阶与注意事项

  • 资源瘦身与分发
    • 图片:转换为 WebP/AVIF,使用 做自适应;启用懒加载。
    • 前端:代码分包、Tree-Shaking、关键 CSS 内联;接入 CDN 做静态资源分发与缓存。
  • 安全与信息泄露
    • 隐藏版本信息:ServerTokens Prod(减少攻击面信息暴露)。
  • 监控与持续优化
    • 日志分析:GoAccess 快速洞察访问与性能瓶颈。
    • 监控告警:Prometheus + Grafana 观测 CPU/内存/连接数/响应时延,结合压测迭代参数。

0