浏览文章

文章信息

怎样在Magento2中配置varnish缓存|How To Configure Varnish In Apache With Magento 2? 1231

Magento 是一个内置于 PHP、Zend 框架和 MySQL 数据库的内容管理系统 (CMS)。这是一个免费的开源系统。如果您从事电子商务业务,那么 Magento 将是一个非常重要的电子商务 Web 应用程序适用于与许多其他开源应用程序(如 Apache、MySQL 等)一起运行的您。现在进一步定义,Apache 是最流行的网络服务器软件之一,它验证计算机是否可以托管一个或多个网站,这些网站可以使用网络浏览器在互联网上进行检查。1995 年,Apache Group 发布了其第一个版本的 Apache。企业的数字化存在与日俱增,在高速互联网时代,您的网站速度对于增加收入数字很重要。您是否因 Magento 2 和 apache 服务器的速度而受苦?在这里,我们提出了如何通过配置 Varnish 来提升您的 Magento 商店的解决方案。Varnish 和 Magento 2 的结合在提高网站整体性能方面非常受欢迎。那么,让我们开始吧。


1) 在服务器上安装 Varnish

● 使用 putty 或终端连接您的服务器并运行以下命令安装 varnish

sudo apt-get install varnish

● 安装Varnish后,您可以通过运行以下命令检查已安装的Varnish版本

varnishd -V

2) 在 Magento 中配置 Varnish

第1步

● 登录到 Magento 管理面板
● 转到 Store > Configuration > General > Web > Base URLs (Secure)
● 将 Offloader 标头从 SSL_OFFLOADED 更改为 X-Forwarded-Proto 并保存配置

第2步

● 转到商店-> 配置-> 高级-> 系统-> 整页缓存
● 将缓存应用程序从内置缓存更改为Varnish缓存(推荐)。
● 刷新 Magento 缓存

3) 在服务器上添加 varnish.vcl

● 以 root 用户登录 ssh 并将文件 [MAGENTO_ROOT]/var/varnish.vcl 重命名为 [MAGENTO_ROOT]/var/default.vcl
● 通过以下命令转到 varnish 的位置

cd /etc/varnish/

● 将原来的default.vcl 文件备份,将Magento 导出的default.vcl 文件放入。

mv default.vcl default.vcl.original
mv /var/www/html/magento/var/default.vcl .

提示:mv /var/www/html/magento/var/default.vcl . 的意思是将Magento目录下的var/default.vcl 搬迁到/etc/varnish/目录。

你也可以使用优化后的vcl文件:

vcl 4.1;
import std;
backend default {
    .host = "localhost";
    .port = "8080";
    .first_byte_timeout = 600s;
    .probe = {
        .url = "/health_check.php";
        .timeout = 2s;
        .interval = 5s;
        .window = 10;
        .threshold = 5;
   }
}
# Add hostnames, IP addresses and subnets that are allowed to purge content
acl purge {
    "localhost";
    "127.0.0.1";
    "::1";
}
sub vcl_recv {
    # Remove empty query string parameters
    # e.g.: www.example.com/index.html?    
    if (req.url ~ "\?$") {
        set req.url = regsub(req.url, "\?$", "");
    }
    # Remove port number from host header
    set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");
    
    # Sorts query string parameters alphabetically for cache normalization purposes    
    set req.url = std.querysort(req.url);
    
    # Remove the proxy header to mitigate the httpoxy vulnerability
    # See https://httpoxy.org/    
    unset req.http.proxy;
    # Add X-Forwarded-Proto header when using https
    if (!req.http.X-Forwarded-Proto && (std.port(server.ip) == 443)) {
        set req.http.X-Forwarded-Proto = "https";
    }
    
    # Reduce grace to 300s if the backend is healthy
    # In case of an unhealthy backend, the original grace is used
    if (std.healthy(req.backend_hint)) {
        set req.grace = 300s;
    }
    
    # Purge logic to remove objects from the cache
    # Tailored to Magento's cache invalidation mechanism
    if (req.method == "PURGE") {
        if (client.ip !~ purge) {
            return (synth(405, "Method not allowed"));
        }
        if (!req.http.X-Magento-Tags-Pattern && !req.http.X-Pool) {
            return (synth(400, "X-Magento-Tags-Pattern or X-Pool header required"));
        }
        if (req.http.X-Magento-Tags-Pattern) {
          ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern);
        }
        if (req.http.X-Pool) {
          ban("obj.http.X-Pool ~ " + req.http.X-Pool);
        }
        return (synth(200, "Purged"));
    }
    
    # Only handle relevant HTTP request methods
    if (req.method != "GET" &&
        req.method != "HEAD" &&
        req.method != "PUT" &&
        req.method != "POST" &&
        req.method != "PATCH" &&
        req.method != "TRACE" &&
        req.method != "OPTIONS" &&
        req.method != "DELETE") {
          return (pipe);
    }
    
    # Only cache GET and HEAD requests
    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }
    # Don't cache the checkout page
    if (req.url ~ "/checkout") {
        return (pass);
    }
    # Don't cache the health check page
    if (req.url ~ "^/(pub/)?(health_check.php)$") {
        return (pass);
    }
    # Collapse multiple cookie headers into one
    std.collect(req.http.Cookie);
    # Remove tracking query string parameters used by analytics tools
    if (req.url ~ "(\?|&)(gclid|cx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=") {
        set req.url = regsuball(req.url, "(gclid|cx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=[-_A-z0-9+()%.]+&?", "");
        set req.url = regsub(req.url, "[?|&]+$", "");
    }
    # Don't cache the authenticated GraphQL requests
    if (req.url ~ "/graphql" && req.http.Authorization ~ "^Bearer") {
        return (pass);
    }
    return (hash);
}
sub vcl_hash {
    # Add a cache variation based on the X-Magento-Vary cookie
    if (req.http.cookie ~ "X-Magento-Vary=") {
        hash_data(regsub(req.http.cookie, "^.*?X-Magento-Vary=([^;]+);*.*$", "\1"));
    } else {
        hash_data("");
    }
    
    # Create cache variations depending on the request protocol
    hash_data(req.http.X-Forwarded-Proto);
    # Create store and currency cache variations for GraphQL requests
    if (req.url ~ "/graphql") {
        hash_data(req.http.Store);
        hash_data(req.http.Content-Currency);
    }
}
sub vcl_backend_response {
	# Serve stale content for three days after object expiration
	# Perform asynchronous revalidation while stale content is served
    set beresp.grace = 3d;
    # All text-based content can be parsed as ESI
    if (beresp.http.content-type ~ "text") {
        set beresp.do_esi = true;
    }
    # Allow GZIP compression on all JavaScript files and all text-based content
    if (bereq.url ~ "\.js$" || beresp.http.content-type ~ "text") {
        set beresp.do_gzip = true;
    }
    
    # Add debug headers
    if (beresp.http.X-Magento-Debug) {
        set beresp.http.X-Magento-Cache-Control = beresp.http.Cache-Control;
    }
    # Only cache HTTP 200 & HTTP 404 responses
    if (beresp.status != 200 && beresp.status != 404) {
        set beresp.ttl = 120s;
        set beresp.uncacheable = true;
        return (deliver);
    # Don't cache private responses
    } elsif (beresp.http.Cache-Control ~ "private") {
        set beresp.uncacheable = true;
        set beresp.ttl = 86400s;
        return (deliver);
    }
    # Remove the Set-Cookie header for cacheable content
    # Only for HTTP GET & HTTP HEAD requests
    if (beresp.ttl > 0s && (bereq.method == "GET" || bereq.method == "HEAD")) {
        unset beresp.http.set-cookie;
    }
   
    # Don't cache content with a negative TTL
    # Don't cache content for no-cache or no-store content
    # Don't cache content where all headers are varied
    if (beresp.ttl <= 0s ||
       beresp.http.Surrogate-control ~ "no-store" ||
       (!beresp.http.Surrogate-Control &&
       beresp.http.Cache-Control ~ "no-cache|no-store") ||
       beresp.http.Vary == "*") {
        set beresp.ttl = 120s;
        set beresp.uncacheable = true;
    }
    return (deliver);
}
sub vcl_deliver {
    # Add debug headers
    if (resp.http.X-Magento-Debug) {
        if (obj.uncacheable) {
            set resp.http.X-Magento-Cache-Debug = "UNCACHEABLE";
        } else if (obj.hits) {
            set resp.http.X-Magento-Cache-Debug = "HIT";
            set resp.http.Grace = req.http.grace;
        } else {
            set resp.http.X-Magento-Cache-Debug = "MISS";
        }
    } else {
        unset resp.http.Age;
    }
    # Don't let browser cache non-static files
    if (resp.http.Cache-Control !~ "private" && req.url !~ "^/(pub/)?(media|static)/") {
        set resp.http.Pragma = "no-cache";
        set resp.http.Expires = "-1";
        set resp.http.Cache-Control = "no-store, no-cache, must-revalidate, max-age=0";
    }
    
    # Cleanup headers
    unset resp.http.X-Magento-Debug;
    unset resp.http.X-Magento-Tags;
    unset resp.http.X-Powered-By;
    unset resp.http.Server;
    unset resp.http.X-Varnish;
    unset resp.http.Via;
    unset resp.http.Link;
}


4)检查DAEMON_OPTS

● 打开/etc/default/varnish,找到DAEMON_OPTS。修改内容如下:

DAEMON_OPTS=”-a :80 \
T localhost:6082\
f /etc/varnish/default.vcl\p
thread_pool_min=1\
p thread_pool_max=1500\
p http_resp_hdr_len=42000\
p http_resp_size=98304\
S /etc/varnish/secret\
s malloc,768m”

5) 将varnish端口从 6081 更改为 80

要将 varnish 端口从 6081 更改为 80,我们需要编辑系统服务配置如下:

vim /etc/systemd/system/multi-user.target.wants/varnish.service

上述命令将打开一个文件,您需要在其中找到如下行:

ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :6081 -T 127.0.0.1:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

● 并用井号注释如下:

#ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :6081 -T 127.0.0.1:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

● 在该行下方,添加如下一行:

ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T 127.0.0.1:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,1536m

6)将Apache监听端口从80改为8080

● 打开 Apache ports 配置文件,修改如下:

vim /etc/apache2/ports.conf
# 将 Listen 80 改成 Listen 8080
vim /etc/apache2/sites-available/magento.conf
# 将 <VirtualHost *:80> 改成  <VirtualHost *:8080>

提示:以上意思是将httpd的监听端口改成8080,原网站的端口也就改成了8080,用户访问80,走的是varnish,varnish判断没有缓存再走8080去获取原网页,然后缓存起来,再返回给客户。https的等下再说

7)重启varnish和apache服务

● 现在我们需要运行以下命令来重启 varnish 和 apache 服务并检查它们的状态:

sudo systemctl daemon-reload
sudo service apache2 restart
sudo service apache2 status
sudo service varnish restart
sudo service varnish status

● 可以通过以下命令查看端口:

 sudo netstat -ltnp | grep:80

提示:你要验证varnish是不是在监听80,httpd(apache)是不是在监听8080。

8) 为 HTTPS 或 SSL 配置 Varnish

● 要使varnish 使用HTTPS 或SSL,您需要进行反向代理。对于反向代理,您必须启用以下模式:

sudo a2enmod SSL
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http

如果是宝塔:注意开启这几个模块就行,一般是开启的。

● 要启用反向代理,请执行以下操作:

sudo vim /etc/apache2/sites-available/magento-ssl.conf

● 找到 SSLEngine on 并在 SSLEngine on 之前粘贴以下行

ProxyPreserveHost On
ProxyPass / http://127.0.0.1:80
RequestHeader set X-Forwarded-Port “443
RequestHeader set X-Forwarded-Proto “https”

● 通过以下命令重新启动 apache:

sudo service apache2 restart

● 另外,通过以下命令检查 apache 的状态:

sudo service apache2 status

9) 验证varnish缓存是否正常工作

● 要验证varnish 是否正常工作,可以通过以下命令进行检查:

curl -I -v –location-trusted 'https://www.example.com'

● 使用以下命令将为您提供前往后端(未命中)的 URL 请求的更新列表。

varnishtop -i BereqURL

●以下命令将为您提供所有请求的更新列表。

varnishtop -i ReqURL

●验证首页是否有X-Varnish头部标识,有就说明正常工作。

varnishlog -g request -q "ReqUrl eq '/'"


10) 如何去除(卸载) Varnish

● 在 Magento2配置中切换回原来的全页缓存。

● Sudo apt-get purge –auto-remove varnish
● 在 apache 和 conf 文件中,将端口更改为 80。

● 重启apache

sudo service apache2 restart


原创