温馨提示×

Ubuntu Apache2如何优化网站内容

小樊
38
2025-12-20 23:35:36
栏目: 云计算

Ubuntu Apache2 网站内容优化实操指南

一 启用压缩与缓存

  • 启用模块
    • 执行:sudo a2enmod deflate headers expires
  • 配置 Gzip 压缩(建议写入站点配置或 /etc/apache2/conf-available/deflate.conf 并软链启用)
    • 要点:对文本类资源开启压缩,并添加 Vary: Accept-Encoding 以适配代理/浏览器差异
    • 示例:
      <IfModule mod_deflate.c>
          AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json
          Header append Vary Accept-Encoding
      </IfModule>
      
  • 配置浏览器缓存(建议写入站点配置或 /etc/apache2/conf-available/expires.conf
    • 示例:
      <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"
      </IfModule>
      
  • 说明
    • 对已经压缩过的资源(如 JPEG/PNG/PDF)再次 Gzip 收益很小,可排除;压缩级别建议取 1–6,在压缩率与 CPU 之间平衡。

二 启用 HTTP/2 与 KeepAlive

  • 启用 HTTP/2
    • 执行:sudo a2enmod http2
    • 在虚拟主机配置中加入:Protocols h2 http/1.1
    • 注意:需 HTTPS;确保 Apache ≥ 2.4.5 且 MPM 为 event/prefork(按需调整)
  • 优化 KeepAlive
    • 建议值(写入 apache2.conf<IfModule mpm_event_module> 或对应 MPM 段落):
      KeepAlive On
      MaxKeepAliveRequests 100
      KeepAliveTimeout 5
      
  • 作用
    • HTTP/2 多路复用降低连接开销;KeepAlive 复用 TCP 连接减少握手次数,提升并发与首包时间。

三 内容层面优化

  • 启用 HTTPS 与自动续期
    • 执行:sudo apt update && sudo apt install certbot python3-certbot-apache
    • 申请证书:sudo certbot --apache -d yourdomain.com
  • SEO 友好 URL 与重写
    • 启用模块:sudo a2enmod rewrite
    • 示例(前端单页应用或美化 URL):
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
      
  • 图片与资源
    • <img> 添加 alt 属性;使用 WebP/AVIF 或工具(如 imagemin)压缩图片
  • 站点地图与规范化
    • 放置 sitemap.xml 于站点根目录,并在 robots.txt 声明:Sitemap: https://yourdomain.com/sitemap.xml
    • 使用 canonical 标签避免重复内容:<link rel="canonical" href="https://yourdomain.com/page-url">
  • 说明
    • 以上措施提升可抓取性、可索引性与加载体验,间接促进 SEO 与转化。

四 验证与上线

  • 配置检查与生效
    • 语法检查:sudo apache2ctl configtest
    • 重启服务:sudo systemctl restart apache2
  • 验证要点
    • 响应头检查:
      • 压缩:响应包含 Content-Encoding: gzip
      • 缓存:存在 Cache-ControlExpires
      • 协议:响应头出现 HTTP/2(如 h2
    • 在线工具:使用 WebPageTestGTmetrix 或浏览器 DevTools Network 面板核对指标与资源大小
  • 可选:反向代理/内容缓存
    • 如需进一步提升边缘命中与吞吐,可启用 mod_cache/mod_cache_disk(适合静态资源或反向代理场景)。

0