在Apache配置中优化静态资源可以通过多种方式实现,以提高网站的性能和加载速度。以下是一些常见的优化方法:
通过启用Gzip压缩可以显著减少传输的数据量。
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
通过设置缓存头,可以让浏览器缓存静态资源,减少重复请求。
<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>
KeepAlive允许客户端在一个TCP连接上发送多个请求,减少连接建立和关闭的开销。
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
将静态资源放在CDN(内容分发网络)上可以显著提高加载速度,因为CDN可以将资源缓存到全球各地的服务器上,用户可以从最近的服务器获取资源。
使用适当的图片格式(如WebP),并压缩图片大小。
AddType image/webp .webp
HTTP/2支持多路复用、头部压缩等特性,可以显著提高性能。
LoadModule http2_module modules/mod_http2.so
Listen 443 https
Protocols h2 http/1.1
禁用不需要的模块可以减少服务器的内存和CPU使用。
# 禁用不必要的模块
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule dir_module modules/mod_dir.so
合理使用Alias和Redirect指令,将静态资源指向正确的路径。
Alias /static/ "/var/www/static/"
<Directory "/var/www/static">
Require all granted
</Directory>
添加安全头可以提高网站的安全性。
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
设置适当的缓存控制头,可以让浏览器缓存静态资源。
<FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
通过以上方法,可以显著优化Apache服务器上的静态资源加载速度和性能。根据具体需求和环境,可以选择合适的优化策略。