优化Apache2配置提升网站速度的关键方法
MPM是Apache处理并发请求的核心组件,需根据服务器硬件(CPU核心数、内存)选择合适类型并优化参数:
<IfModule mpm_event_module>
StartServers 2 # 初始子进程数
MinSpareThreads 25 # 最小空闲线程数
MaxSpareThreads 75 # 最大空闲线程数
ThreadLimit 64 # 线程数上限
ThreadsPerChild 25 # 每个子进程创建的线程数
MaxRequestWorkers 150 # 最大并发请求数(根据内存调整,每线程约占用10MB内存)
MaxConnectionsPerChild 0 # 子进程处理请求数上限(0表示无限制)
</IfModule>
修改后需重启Apache生效。KeepAlive允许客户端通过单个TCP连接发送多个请求,降低TCP握手/挥手的网络延迟:
KeepAlive On # 启用KeepAlive
MaxKeepAliveRequests 100 # 单个连接最大请求数(避免单个连接占用过久)
KeepAliveTimeout 5 # 连接保持超时时间(秒,超过则关闭)
需权衡:过长的Timeout会增加服务器资源占用,过短则无法发挥KeepAlive优势。
使用mod_deflate
模块压缩HTML、CSS、JavaScript等文本资源,可减少约50%-70%的传输数据量:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/x-javascript
DeflateCompressionLevel 9 # 压缩级别(1-9,9为最高,但会消耗更多CPU)
DeflateBufferSize 16384 # 缓冲区大小(字节,推荐16KB-64KB)
</IfModule>
验证:可通过浏览器开发者工具(Network面板)查看响应头中的Content-Encoding: gzip
确认启用。
通过mod_cache
(内存/磁盘缓存)和mod_expires
(浏览器缓存)减少重复请求:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk / # 启用根目录缓存
CacheRoot "/var/cache/apache2/mod_cache_disk" # 缓存目录(需手动创建并赋予权限:chown -R www-data:www-data /var/cache/apache2)
CacheDirLevels 2 # 缓存目录层级(避免单目录文件过多)
CacheDirLength 1 # 每层目录名长度
CacheDefaultExpire 3600 # 默认缓存过期时间(秒,1小时)
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 week" # HTML缓存1周
ExpiresByType text/css "access plus 1 month" # CSS缓存1个月
ExpiresByType application/javascript "access plus 1 month" # JS缓存1个月
ExpiresByType image/jpeg "access plus 1 year" # JPEG图片缓存1年
ExpiresByType image/png "access plus 1 year" # PNG图片缓存1年
</IfModule>
缓存目录权限需设置为Apache用户(如www-data
),避免写入失败。Apache默认加载大量模块,禁用未使用的模块可减少内存占用:
# 查看已启用模块
apache2ctl -M
# 禁用模块(如auth_basic、autoindex,根据需求选择)
sudo a2dismod auth_basic autoindex
# 重启Apache
sudo systemctl restart apache2
仅保留必需模块(如mod_rewrite
、mod_ssl
)。
LogLevel
从info
改为warn
或error
,减少不必要的日志输出:LogLevel warn
<FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
SetEnvIf Request_URI "\.(jpg|jpeg|png|gif|css|js)$" dontlog
</FilesMatch>
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
日志文件过大时可使用logrotate
工具自动分割。将静态资源(图片、CSS、JS、字体)部署到CDN节点,减少用户访问的物理距离和服务器负载:
https://cdn.example.com/static/image.jpg
)。mod_rewrite
模块强制静态资源走CDN:RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^static/(.*)$ https://cdn.example.com/static/$1 [L,R=301]
HTTP/2支持多路复用(一个连接并行处理多个请求),减少延迟:
# 安装mod_http2模块(Ubuntu/Debian)
sudo apt install libapache2-mod-http2
# 启用模块
sudo a2enmod http2
# 在配置文件中启用HTTP/2
<IfModule http2_module>
Protocols h2 http/1.1
</IfModule>
# 重启Apache
sudo systemctl restart apache2
需注意:HTTP/2需配合TLS(HTTPS)使用。
/etc/sysctl.conf
中的参数,优化网络性能:net.ipv4.tcp_tw_reuse = 1 # 复用TIME-WAIT状态的连接
net.ipv4.tcp_max_syn_backlog = 4096 # SYN队列长度
net.core.somaxconn = 4096 # 监听队列长度
修改后执行sudo sysctl -p
生效。