温馨提示×

Apache配置Ubuntu下如何优化静态资源

小樊
46
2025-11-03 02:23:04
栏目: 智能运维

在Ubuntu下优化Apache服务器以提供更好的静态资源服务,可以通过以下几个方面来实现:

1. 启用压缩

启用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. 优化MIME类型

确保Apache正确识别和提供静态文件的MIME类型。

编辑/etc/mime.types文件,确保包含以下内容:

types-config mime.types

然后重启Apache:

sudo systemctl restart apache2

5. 使用CDN

如果可能,使用内容分发网络(CDN)来分发静态资源,可以显著提高加载速度和减少服务器负载。

6. 优化日志记录

减少日志记录的频率和详细程度可以减少磁盘I/O操作。

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

LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
SetEnvIf Request_URI "\.(?:gif|jpe?g|png)$" dontlog
SetEnvIf Request_URI "\.(?:ico|css|js|js2|js3|js4|woff|ttf|svg)$" dontlog

然后重启Apache:

sudo systemctl restart apache2

通过以上步骤,你可以显著优化Apache服务器在Ubuntu下的静态资源服务。

0