侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

Apache/httpd(11)之启用响应压缩功能

zze
zze
2020-01-03 / 0 评论 / 0 点赞 / 602 阅读 / 2397 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

在 httpd 中提供了一个 mod_deflate 模块,该模块能够在 httpd 服务器响应时对我们设定的特定类型的资源进行压缩。
使用场景:

  1. 节约带宽,额外消耗CPU,同时,可能有些较老浏览器不支持;
  2. 压缩适于压缩的资源,例如文件文件;

查看 /etc/httpd/conf/httpd.conf 文件可以看到该模块默认就已被启用:

$ cat /etc/httpd/conf/httpd.conf | grep deflate
LoadModule deflate_module modules/mod_deflate.so

除此以外还需在该配置文件中加入以下配置,各配置项描述在注释中:

# 使用 DEFLATE 作为输出过滤器
SetOutputFilter DEFLATE 

# mod_deflate configuration

# 设定过滤资源的 MIME 类型
# Restrict compression to these MIME types
AddOutputFilterByType DEFLATE text/plain 
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/css

# 指定压缩级别
# Level of compression (Highest 9 - Lowest 1)
DeflateCompressionLevel 9
 
# 对匹配到的浏览器类型定制压缩规则

# 仅对 text/html 压缩
# Netscape 4.x has some problems.
BrowserMatch ^Mozilla/4  gzip-only-text/html
 
# 不使用 gzip 压缩
# Netscape 4.06-4.08 have some more problems
BrowserMatch  ^Mozilla/4\.0[678]  no-gzip

# 不使用 gzip 压缩,不使用 gzip 对 text/html 资源压缩
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSI[E]  !no-gzip !gzip-only-text/html

/etc/httpd/conf/httpd.conf 中添加完上述配置后重启或重新加载服务,随便访问一个资源:

$ curl -I 10.0.1.201/test/hello.html
HTTP/1.1 200 OK
Date: Thu, 02 Jan 2020 10:01:55 GMT
Server: Apache/2.2.15 (CentOS)
Last-Modified: Thu, 02 Jan 2020 09:44:46 GMT
ETag: "620f2-4ce8-59b250b20031a"
Accept-Ranges: bytes
Content-Length: 19688
Vary: Accept-Encoding
Connection: close
Content-Type: text/html; charset=UTF-8

可以看到未使用压缩时响应长度为 19688
再使用 curl 设定允许压缩的情况看下:

$ curl -I --compressed 10.0.1.201/test/hello.html
HTTP/1.1 200 OK
Date: Thu, 02 Jan 2020 10:03:21 GMT
Server: Apache/2.2.15 (CentOS)
Last-Modified: Thu, 02 Jan 2020 09:44:46 GMT
ETag: "620f2-4ce8-59b250b20031a"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 6412
Connection: close
Content-Type: text/html; charset=UTF-8

可以看到压缩后的长度为 6412,几乎是文件原长度的三分之一。

0

评论区