在Ubuntu上优化Apache2服务器以提供静态文件服务,可以通过以下步骤来实现:
确保启用了mod_deflate
、mod_expires
和mod_headers
模块,这些模块可以帮助压缩和缓存静态文件。
sudo a2enmod deflate
sudo a2enmod expires
sudo a2enmod headers
编辑Apache配置文件(通常是/etc/apache2/apache2.conf
或/etc/apache2/sites-available/000-default.conf
),添加以下内容以启用Gzip压缩:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
使用mod_expires
模块来设置静态文件的缓存策略。编辑Apache配置文件,添加以下内容:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
</IfModule>
使用mod_headers
模块来设置缓存控制头。编辑Apache配置文件,添加以下内容:
<IfModule mod_headers.c>
<FilesMatch "\.(jpg|jpeg|png|gif|ico|css|js)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
</IfModule>
KeepAlive可以减少TCP连接的建立和关闭次数,从而提高性能。编辑Apache配置文件,找到<IfModule mpm_prefork_module>
部分,确保启用了KeepAlive:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
</IfModule>
完成上述配置后,重启Apache服务器以应用更改:
sudo systemctl restart apache2
对于高流量的网站,考虑使用内容分发网络(CDN)来进一步优化静态文件的传输速度。
通过以上步骤,你可以显著提高Ubuntu上Apache2服务器提供静态文件的性能。