ubuntu

Ubuntu Apache如何优化静态资源加载

小樊
42
2025-10-17 00:33:32
栏目: 智能运维

在Ubuntu上使用Apache优化静态资源加载,可以通过以下几种方法来提高性能和加载速度:

1. 启用压缩

启用Gzip压缩可以显著减少传输的数据量。

sudo a2enmod deflate
sudo systemctl restart apache2

2. 启用缓存

通过配置Apache的缓存模块,可以减少对服务器的请求次数。

启用mod_expires

sudo a2enmod expires

编辑/etc/apache2/conf-available/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/pdf "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

然后重启Apache:

sudo systemctl restart apache2

启用mod_cache

sudo a2enmod cache
sudo a2enmod cache_disk

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

<IfModule mod_cache.c>
    <IfModule mod_cache_disk.c>
        CacheRoot /var/cache/apache2/mod_cache_disk
        CacheEnable disk /
        CacheDirLevels 2
        CacheDirLength 1
    </IfModule>
</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. 优化静态文件目录

将静态文件放在一个单独的目录中,并配置Apache直接提供这些文件,可以减少对动态内容的处理。

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

<Directory /var/www/your-site/static>
    Options -Indexes +FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Alias /static/ /var/www/your-site/static/

<Directory /var/www/your-site/static>
    Require all granted
</Directory>

然后重启Apache:

sudo systemctl restart apache2

5. 使用CDN

将静态资源托管到CDN(内容分发网络)可以显著提高加载速度,因为CDN可以将资源缓存到全球各地的服务器上。

6. 启用HTTP/2

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

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

LoadModule http2_module /usr/lib/apache2/modules/mod_http2.so

<IfModule http2_module>
    Protocols h2 http/1.1
</IfModule>

然后重启Apache:

sudo systemctl restart apache2

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

0
看了该问题的人还看了