要优化Apache2服务器上的静态资源加载,可以采取以下措施:
使用mod_deflate
模块来压缩静态文件,减少传输大小。
sudo a2enmod deflate
然后在/etc/apache2/mods-enabled/deflate.conf
中添加以下配置:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
使用mod_expires
和mod_headers
模块来设置静态资源的缓存策略。
sudo a2enmod expires
sudo a2enmod headers
然后在/etc/apache2/conf-available/static-site.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"
ExpiresByType application/x-javascript "access plus 1 month"
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "max-age=31536000, public"
</IfModule>
确保mod_deflate
模块已启用,并在/etc/apache2/apache2.conf
或/etc/apache2/httpd.conf
中添加以下配置:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
将静态资源托管到CDN(内容分发网络),可以显著提高加载速度,减少服务器负载。
启用KeepAlive
可以减少TCP连接的建立和关闭次数,提高传输效率。
在/etc/apache2/apache2.conf
或/etc/apache2/httpd.conf
中添加:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
使用工具如ImageOptim
、TinyPNG
等来压缩图片,减少文件大小。
确保服务器支持并启用了HTTP/2协议,它可以显著提高多路复用和头部压缩的效率。
在/etc/apache2/apache2.conf
或/etc/apache2/httpd.conf
中添加:
LoadModule http2_module modules/mod_http2.so
Protocols h2 http/1.1
禁用不需要的Apache模块可以减少内存使用和提高性能。
sudo a2dismod <module_name>
确保静态资源的缓存控制头设置正确,以便浏览器可以缓存资源。
<IfModule mod_headers.c>
<FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
</IfModule>
使用工具如Apache Bench
、WebPageTest
等来监控和分析服务器性能,找出瓶颈并进行优化。
通过以上措施,可以显著提高Apache2服务器上静态资源的加载速度和性能。