温馨提示×

Ubuntu Apache2如何优化静态资源

小樊
38
2025-03-11 02:07:47
栏目: 智能运维
Ubuntu服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu上使用Apache2优化静态资源可以通过多种方式实现,以下是一些常见的优化方法:

1. 启用Gzip压缩

Gzip压缩可以显著减少传输的数据量,从而加快页面加载速度。

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>

然后重启Apache:

sudo systemctl restart apache2

2. 启用缓存

使用Apache的mod_expires模块来设置静态资源的缓存策略。

sudo a2enmod expires

编辑/etc/apache2/mods-enabled/expires.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>

然后重启Apache:

sudo systemctl restart apache2

3. 启用KeepAlive

KeepAlive允许客户端在一个TCP连接上发送多个请求,减少连接建立的开销。

编辑/etc/apache2/apache2.conf文件,找到并修改以下内容:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

然后重启Apache:

sudo systemctl restart apache2

4. 使用CDN

将静态资源放在CDN(内容分发网络)上可以显著提高加载速度,因为CDN可以将资源缓存到全球各地的服务器上,用户可以从最近的服务器获取资源。

5. 优化图片

使用工具如imagemin来压缩图片,减少图片的大小。

sudo apt-get install imagemin

然后使用imagemin命令来压缩图片:

imagemin --lossy --quality 75 *.jpg

6. 启用HTTP/2

HTTP/2提供了多路复用、头部压缩等特性,可以显著提高性能。

确保你的Apache版本支持HTTP/2,并且已经安装了mod_http2模块。

sudo a2enmod http2

编辑/etc/apache2/apache2.conf文件,添加以下内容:

<IfModule mod_http2.c>
    Protocols h2 http/1.1
</IfModule>

然后重启Apache:

sudo systemctl restart apache2

7. 使用缓存控制头

通过设置适当的缓存控制头,可以进一步优化静态资源的加载。

编辑/etc/apache2/sites-available/your-site.conf文件,添加以下内容:

<IfModule mod_headers.c>
    <FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
        Header set Cache-Control "max-age=31536000, public"
    </FilesMatch>
</IfModule>

然后重启Apache:

sudo systemctl restart apache2

通过以上方法,你可以显著优化Ubuntu上Apache2服务器的静态资源加载速度。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Ubuntu Apache2如何优化静态资源加载

0