debian

如何在Debian上启用压缩缓存

小樊
53
2025-09-29 17:31:13
栏目: 智能运维

在Debian上启用压缩缓存可以显著提高文件传输和网络访问的速度。以下是一些常见的方法来启用压缩缓存:

1. 使用 squid 代理服务器

squid 是一个高性能的缓存代理服务器,支持压缩缓存。

安装 squid

sudo apt update
sudo apt install squid

配置 squid

编辑 /etc/squid/squid.conf 文件,添加或修改以下配置:

http_access allow all
acl localnet src 192.168.1.0/24  # 根据你的网络配置修改
acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT

http_port 3128 accel defaultsite=my_cache_host
cache_mem 64 MB
maximum_object_size 4 MB
refresh_pattern . 1440 90% 10080 override-expire ignore-reload ignore-no-cache ignore-private

启动 squid

sudo systemctl start squid
sudo systemctl enable squid

2. 使用 nginx 作为反向代理和缓存服务器

nginx 也可以配置为缓存服务器,并支持压缩。

安装 nginx

sudo apt update
sudo apt install nginx

配置 nginx

编辑 /etc/nginx/nginx.conf 或在 /etc/nginx/conf.d/ 目录下创建一个新的配置文件,例如 default.conf

http {
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_pass http://backend_server;
            proxy_cache my_cache;
            proxy_cache_valid 200 302 10m;
            proxy_cache_valid 404 1m;
            add_header X-Proxy-Cache $upstream_cache_status;
        }
    }
}

启动 nginx

sudo systemctl start nginx
sudo systemctl enable nginx

3. 使用 varnish 缓存服务器

varnish 是一个高性能的 HTTP 加速器,也支持压缩。

安装 varnish

sudo apt update
sudo apt install varnish

配置 varnish

编辑 /etc/varnish/default.vcl 文件,添加或修改以下配置:

vcl 4.0;

backend default {
    .host = "127.0.0.1";
    .port = "80";
}

sub vcl_recv {
    if (req.http.Accept-Encoding) {
        if (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
        } elsif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
        } else {
            unset req.http.Accept-Encoding;
        }
    }
}

sub vcl_backend_response {
    if (bereq.http.Accept-Encoding) {
        if (beresp.http.content-encoding ~ "gzip") {
            set beresp.do_gzip = true;
        } elsif (beresp.http.content-encoding ~ "deflate") {
            set beresp.do_gzip = true;
        }
    }
}

启动 varnish

sudo systemctl start varnish
sudo systemctl enable varnish

总结

以上方法都可以在Debian上启用压缩缓存,具体选择哪种方法取决于你的需求和环境。squid 适用于传统的代理服务器场景,nginx 适用于需要同时处理静态和动态内容的场景,而 varnish 则适用于高性能的HTTP加速场景。

0
看了该问题的人还看了