1. 启用压缩传输(mod_deflate)
通过mod_deflate
模块压缩HTML、CSS、JavaScript等文本资源,减少传输数据量,显著提升页面加载速度。配置步骤:
sudo a2enmod deflate
(Debian/Ubuntu)或通过yum install mod_deflate
(CentOS/RHEL)安装并启用。/etc/apache2/apache2.conf
或虚拟主机配置),添加以下规则:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/x-javascript
DeflateCompressionLevel 6 # 压缩级别(1-9,6为平衡性能与压缩比的推荐值)
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|mp3|mp4)$ no-gzip dont-vary # 不压缩已压缩的文件(如图片、视频)
</IfModule>
sudo systemctl restart apache2
。Content-Encoding: gzip
存在。2. 配置静态资源缓存(mod_expires/mod_cache)
通过缓存静态资源(图片、CSS、JS等),减少客户端重复请求,降低服务器负载。配置步骤:
sudo a2enmod expires
(Debian/Ubuntu)或sudo yum install mod_expires
(CentOS/RHEL)。<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year" # JPEG图片缓存1年
ExpiresByType text/css "access plus 1 week" # CSS缓存1周
ExpiresByType application/javascript "access plus 1 week" # JS缓存1周
ExpiresDefault "access plus 1 day" # 默认缓存1天
</IfModule>
mod_cache
模块将缓存存储到磁盘,进一步提升性能:<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /static # 缓存/static路径下的资源
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
curl -I http://yourdomain.com/image.jpg
检查响应头,确认Expires
和Cache-Control
头存在。3. 调整MPM(多处理模块)设置
根据服务器硬件资源(CPU核心数、内存)调整MPM参数,优化并发处理能力。以event
MPM(推荐,适用于高并发场景)为例:
/etc/apache2/mods-enabled/mpm_event.conf
),调整参数:<IfModule mpm_event_module>
StartServers 2 # 启动时的进程数
MinSpareThreads 25 # 最小空闲线程数
MaxSpareThreads 75 # 最大空闲线程数
ThreadLimit 64 # 单个进程的最大线程数
ThreadsPerChild 25 # 每个子进程创建的线程数
MaxRequestWorkers 150 # 最大并发请求数(根据内存调整,每线程约消耗2-4MB内存)
MaxConnectionsPerChild 0 # 每个子进程处理的请求数(0表示无限制)
</IfModule>
MaxRequestWorkers
需根据服务器内存计算(如1GB内存可设置为100-150),避免内存耗尽导致服务器崩溃。4. 启用KeepAlive
通过KeepAlive技术让客户端在单个TCP连接上发送多个请求,减少TCP握手和挥手开销(约占连接建立时间的30%)。配置步骤:
/etc/apache2/apache2.conf
),添加以下参数:KeepAlive On # 启用KeepAlive
MaxKeepAliveRequests 100 # 单个连接允许的最大请求数(避免单个连接占用过久)
KeepAliveTimeout 5 # 连接保持时间(秒,超过则关闭)
KeepAliveTimeout
不宜过长(如超过10秒),否则会导致服务器资源被闲置连接占用。5. 禁用不必要的模块
Apache默认加载许多模块,禁用未使用的模块可减少内存和CPU消耗。操作步骤:
apache2ctl -M
(Debian/Ubuntu)或httpd -M
(CentOS/RHEL)。authn_file
、autoindex
等):sudo a2dismod authn_file autoindex
。sudo systemctl restart apache2
。mod_rewrite
(URL重写)、mod_ssl
(HTTPS)等必需模块。6. 启用HTTP/2协议(mod_http2)
HTTP/2支持多路复用(一个连接并行处理多个请求)、头部压缩等功能,可显著提升页面加载速度(尤其是包含大量资源的页面)。配置步骤:
sudo a2enmod http2
(Debian/Ubuntu)。/etc/apache2/sites-available/your-site.conf
),在<VirtualHost>
块中添加:Protocols h2 http/1.1 # 优先使用HTTP/2,回退到HTTP/1.1
sudo systemctl restart apache2
。h2
。7. 优化SSL/TLS配置(如使用HTTPS)
若网站使用HTTPS,优化SSL配置可减少加密解密带来的性能开销:
<IfModule mod_ssl.c>
SSLUseStapling On
SSLStaplingCache "shmcb:/var/run/stapling-cache(150000)"
</IfModule>
<IfModule mod_ssl.c>
SSLSessionCache shmcb:/var/run/ssl_scache(512000)
SSLSessionCacheTimeout 300 # 会话缓存超时时间(秒)
</IfModule>