温馨提示×

如何利用Linux Apache2提升网站速度

小樊
33
2025-12-08 22:27:08
栏目: 云计算

Linux Apache2 网站加速实操指南

一 基础与连接优化

  • 启用持久连接 KeepAlive,减少 TCP 握手与慢启动带来的开销:
    KeepAlive On
    MaxKeepAliveRequests 100
    KeepAliveTimeout 5
    
  • 启用压缩(mod_deflate),减小传输体积,优先压缩文本类资源:
    sudo a2enmod deflate
    
    在配置中加入:
    <IfModule mod_deflate.c>
      AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
      AddOutputFilterByType DEFLATE image/svg+xml image/x-icon
      AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
      AddOutputFilterByType DEFLATE application/vnd.ms-fontobject application/x-font-ttf font/opentype
    </IfModule>
    
  • 启用 HTTP/2(mod_http2)提升并发与首包时间(需 TLS):
    sudo a2enmod http2
    
    在虚拟主机启用:
    Protocols h2 http/1.1
    
  • 精简模块与进程:仅启用必需模块(如deflate、http2、cache/disk_cache、expires、status),禁用无用模块以减少内存占用与攻击面:
    sudo a2dismod module_name
    
  • 建议同时启用 mod_status 并限制访问,便于观测连接与性能:
    sudo a2enmod status
    
    在配置中:
    ExtendedStatus On
    <Location "/server-status">
      SetHandler server-status
      Require local
    </Location>
    

以上措施能显著降低首字节时间(TTFB)并提升并发处理能力,建议优先实施。

二 缓存策略

  • 客户端强缓存(mod_expires):为静态资源设置长期 Cache-Control/Expires,减少重复请求
    sudo a2enmod expires
    
    配置示例:
    <IfModule mod_expires.c>
      ExpiresActive On
      ExpiresByType text/css "access plus 1 year"
      ExpiresByType application/javascript "access plus 1 year"
      ExpiresByType image/jpeg "access plus 1 year"
      ExpiresByType image/png "access plus 1 year"
      ExpiresByType image/gif "access plus 1 year"
      ExpiresByType text/html "access plus 1 day"
    </IfModule>
    
  • 反向代理/网关缓存(mod_cache + mod_disk_cache):缓存动态页面或代理后端响应,显著降低后端压力
    sudo a2enmod cache
    sudo a2enmod cache_disk
    
    配置示例(按站点或全局):
    <IfModule mod_cache.c>
      <IfModule mod_cache_disk.c>
        CacheEnable disk /
        CacheRoot "/var/cache/apache2/mod_cache_disk"
        CacheDirLevels 2
        CacheDirLength 1
        CacheIgnoreHeaders Set-Cookie
        CacheIgnoreNoLastMod On
        CacheDefaultExpire 3600
        CacheMaxExpire 86400
      </IfModule>
    </IfModule>
    
  • 应用层配合:确保后端返回合适的 Cache-Control / ETag / Last-Modified,对可缓存内容使用版本化文件名(如 app.a1b2c3.js)。
  • 验证:使用 curl 检查响应头
    curl -I https://your-domain/static/app.js
    
    关注 Cache-Control、Expires、ETag 等字段是否生效。 通过“客户端强缓存 + 网关/代理缓存”的组合,可大幅减少源站计算与网络往返。

三 并发与 MPM 调优

  • 选择合适的 MPM(多处理模块)
    • prefork:兼容非线程安全模块(如某些旧版 PHP),稳定但内存占用高。
    • worker/event:线程化,资源占用更低、并发更高;高并发优先 event
  • 调整 MPM 参数(示例为 Ubuntu/Debian 常见路径,CentOS 路径为 /etc/httpd/conf.modules.d/00-mpm.conf/etc/httpd/conf/httpd.conf):
    • prefork(示例,按内存与业务调整):
      <IfModule mpm_prefork_module>
        StartServers          5
        MinSpareServers       5
        MaxSpareServers      10
        ServerLimit         256
        MaxRequestWorkers   256
        MaxConnectionsPerChild 4000
      </IfModule>
      
    • event/worker(示例,关注 MaxRequestWorkers/ThreadsPerChild 与系统资源匹配)
  • 调优要点:
    • MaxRequestWorkers 与内存匹配(每个进程/线程占用内存 × 并发数 ≤ 物理内存 - 系统预留)。
    • 结合监控逐步加压,避免一次性拉满导致 OOM 或抖动。
    • 高并发短连接场景优先 event,长连接或兼容性需求选择 prefork。 合理选择并调优 MPM,是提升吞吐量与稳定性的关键。

四 全链路加速与系统层面优化

  • 使用 CDN 分发静态资源与可缓存内容,降低源站带宽与时延,配合 Cache-Control/ETag 提升命中率。
  • PHP 加速:启用 OPcache(减少脚本编译开销)
    ; php.ini
    opcache.enable=1
    opcache.memory_consumption=128
    opcache.interned_strings_buffer=8
    opcache.max_accelerated_files=4000
    opcache.validate_timestamps=0   ; 生产环境建议关闭,配合部署刷新
    
  • 数据库优化:为高频查询建立合适索引、优化慢查询、合理设置缓冲(如 InnoDB buffer pool),减少后端瓶颈对 Apache 的影响。
  • 系统与网络(可选,按环境评估):
    • 适度提升文件描述符与网络参数(如 net.core.somaxconn、net.ipv4.tcp_tw_reuse)。
    • 使用 SSD、优化文件系统挂载选项(如 noatime),减少 I/O 等待。
    • 静态资源占比高时,可考虑以 Nginx 作为静态资源前置或反向代理,进一步提升并发与静态文件效率。 这些手段从“边缘缓存 + 语言运行时 + 数据层 + 系统资源”多维度协同加速。

五 验证与回滚

  • 配置语法检查与热重载:
    sudo apache2ctl configtest
    sudo systemctl reload apache2   # 或 restart,视变更范围而定
    
  • 验证要点:
    • 压缩生效:响应头出现 Content-Encoding: gzip/deflate(或 br 若启用 Brotli)。
    • 缓存生效:响应头出现 Cache-Control / Expires / ETag,且命中时返回 304
    • HTTP/2:浏览器开发者工具或 curl -I --http2 显示 HTTP/2 200
    • 并发与状态:通过 mod_status 观察 BusyWorkers/IdleWorkers 与请求耗时。
  • 回滚预案:保留备份配置(如 /etc/apache2/conf-available/ 与站点配置),异常时快速恢复并逐步回退变更。
  • 风险提示:并发与缓存策略需结合业务与硬件压测后上线,避免一次性大幅调整导致稳定性问题。

0