http压缩传输方案
- 服务器
- 三生万物
- 0
由于页面加载速度比较慢,所以想尝试下php的压缩传输方式,鼓捣了一段时间,中间还把php集成环境搞挂了,索性数据库找回来了,不然后果很严重。
经过不断探索实践,终于在同事的帮助下解决了,哈哈。下面记录几种解决方案
原理
header("Content-Encoding: gzip");
echo gzencode('songjiankang');
一、php方式
- ob_gzhandler(为php内置函数,具体参考手册)
ob_start('ob_gzhandler');
this.display('index.html');
- 自定义
thinkphp3.x下,函数写在Application/Common/Common/function.php,没有自建
function ob_gzip ($content) { // $content 就是要压缩的页面内容,或者说饼干原料
if (
! headers_sent() && // 如果页面头部信息还没有输出
extension_loaded("zlib") && // 而且zlib扩展已经加载到PHP中
strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip") // 而且浏览器说它可以接受GZIP的页面
) {
$content = gzencode($content . " \n//此页已压缩", 9); // 此页已压缩”的注释标签,然后用zlib提供的gzencode()函数执行级别为9的压缩,这个参数值范围是0-9,0表示无压缩,9表示最大压缩,当然压缩程度越高越费CPU。
// 然后用header()函数给浏览器发送一些头部信息,告诉浏览器这个页面已经用GZIP压缩过了!
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Content-Length: " . strlen($content));
}
return $content; // 返回压缩的内容,或者说把压缩好的饼干送回工作台。
}
使用
ob_start('ob_gzip ');
this.display('index.html');
二、apache方式
打开httpd.conf配置文件
- 加载so
LoadModule headers_module modules/mod_headers.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule filter_module modules/mod_filter.so
- 添加规则
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/json application/x-httpd-php application/x-javascript application/javascript
</IfModule>
三、nginx方式
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#开启gzip
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_types text/css application/javascript image/jpeg image/gif image/png;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
server {
listen 80;
server_name localhost;
client_max_body_size 20M; // 默认1M,加大请求体,上传大文件
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
try_files $uri $uri/ /index.html;
root html/dist;
index index.html index.htm;
chunked_transfer_encoding on; // 开启chunk
}
# 缓存js、css
location ~ .*\.(js|css)?$ {
expires 1h;
}
location /test {
proxy_pass http://www.xxx.com/test;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#...
四、node中间件compression
npm安装地址:https://www.npmjs.com/package/compression
var compression = require('compression'); // 压缩传输
app.use(compression());
参考:
- https://www.cnblogs.com/siqi/p/4003421.html
- https://blog.csdn.net/yutian9793/article/details/78824705
免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。