在CentOS上优化Apache2以加载静态资源,可以通过以下几个方面来实现:
Apache提供了多种缓存模块,如mod_cache
和mod_cache_disk
,可以显著提高静态资源的加载速度。
sudo yum install mod_cache mod_cache_disk
sudo systemctl restart httpd
编辑Apache配置文件(通常是/etc/httpd/conf/httpd.conf
或/etc/httpd/conf.d/
目录下的文件),添加以下内容:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "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/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/json "access plus 1 month"
</IfModule>
启用Gzip压缩可以减少传输数据的大小,从而加快加载速度。
编辑Apache配置文件,添加以下内容:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
使用内容分发网络(CDN)可以将静态资源缓存到全球各地的服务器上,从而加快用户访问速度。
将静态资源的URL指向CDN提供商的URL。例如:
<link rel="stylesheet" href="https://cdn.example.com/styles.css">
<script src="https://cdn.example.com/scripts.js"></script>
优化图片大小和格式可以显著减少加载时间。
WebP是一种现代图片格式,提供更好的压缩率。可以使用cwebp
工具将图片转换为WebP格式。
sudo yum install webp
cwebp -q 80 input.jpg -o output.webp
使用imagemin
等工具压缩图片。
npm install imagemin-cli -g
imagemin input.jpg -o output.jpg --quality=80
KeepAlive允许客户端在一个TCP连接上发送多个请求,减少连接建立的开销。
编辑Apache配置文件,添加以下内容:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
确保Apache正确识别和提供静态资源的MIME类型。
编辑Apache配置文件,添加以下内容:
AddType image/webp .webp
AddType application/javascript .js
AddType text/css .css
HTTP/2提供了多路复用、头部压缩等特性,可以显著提高性能。
确保Apache已安装并启用了mod_http2
模块,并在配置文件中启用HTTP/2:
LoadModule http2_module modules/mod_http2.so
Protocols h2 http/1.1
通过以上步骤,可以显著优化CentOS上Apache2服务器的静态资源加载速度。