在Ubuntu中优化Apache2以加载静态资源,可以通过以下步骤进行:
启用压缩:
mod_deflate模块来压缩文本文件(如HTML、CSS和JavaScript)。sudo a2enmod deflate
/etc/apache2/apache2.conf或/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模块来设置静态资源的过期时间。sudo a2enmod expires
<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>
启用Gzip压缩:
mod_gzip模块已启用(如果可用)。sudo a2enmod gzip
<IfModule mod_gzip.c>
AddOutputFilterByType GZIP text/html text/plain text/xml text/css application/javascript
</IfModule>
优化KeepAlive:
KeepAlive和MaxKeepAliveRequests参数。KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
调整文件描述符限制:
/etc/security/limits.conf文件,增加文件描述符的限制。* soft nofile 10240
* hard nofile 20480
调整内核参数:
/etc/sysctl.conf文件,添加或修改以下内容:net.core.somaxconn = 1024
net.ipv4.tcp_max_syn_backlog = 1024
net.ipv4.ip_local_port_range = 1024 65535
sudo sysctl -p
使用CDN:
优化静态文件路径:
sudo chown -R www-data:www-data /var/www/html/static
sudo chmod -R 755 /var/www/html/static
重启Apache:
sudo systemctl restart apache2
通过以上步骤,可以显著提高Apache2在Ubuntu系统中加载静态资源的性能。