Magento接入Varnish
Varnish是一款高性能的开源HTTP加速器,可以有效降低web服务器的负载,提升访问速度。根据官方的说法,Varnish是一个cache型的HTTP反向代理。
基于M2.3.5和Varnish4.x
安装Varnish
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
yum update && yum install varnish
配置Varnish
vim /etc/varnish/varnish.params
VARNISH_LISTEN_PORT=6081
VARNISH_ADMIN_LISTEN_PORT=6082
DAEMON_OPTS="-a :6081
-T localhost:6082
-f /etc/varnish/default.vcl
-S /etc/varnish/secret
-p thread_pool_min=5
-p thread_pool_max=500 \
-p http_resp_hdr_len=65536
-p http_resp_size=98304
-p workspace_backend=98304 \
-s malloc,256m"
cp /etc/varnish/default.vcl /etc/varnish/default.vcl.bak
M2配置
Stores
- Configuration
- Advanced
- System
- Full Page Cache
然后将后台导出default.vcl
上传到服务器,如果使用Nginx
,还需要将/pub/health_check.php
改为/health_check.php
。
启动Varnish
systemctl start varnish
Nginx配置
map $request_uri $MAGE_RUN_CODE {
default base;
}
map $request_uri $MAGE_RUN_TYPE {
default website;
}
server {
listen 80;
server_name test.magento.com;
location / {
proxy_pass http://127.0.0.1:6081;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name test.magento.com;
#ssl on;
ssl_certificate /usr/local/nginx/client_body_temp/2547820_test.magento.com.pem;
ssl_certificate_key /usr/local/nginx/client_body_temp/2547820_test.magento.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:6081;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Port 443;
}
}
server {
listen 8080;
server_name test.magento.com;
set $MAGE_ROOT /var/www/html/magento;
include /var/www/html/magento/nginx.conf.sample;
}
用户通过http(80端口)或者https(443端口)访问时,使用Nginx的proxy_pass
命令,反向代理到6081
端口,由Varnish返回数据。
绑定varnish主机
bin/magento setup:config:set --http-cache-hosts=127.0.0.1:6081
这样,使用cache:clean
就能同时把Varnish的缓存清理掉了。
正向代理和反向代理
题外话,无论正向代理还是反向代理,其实都是使用proxy_pass命令实现。正向还是反向,可以看代理的对象是客户端还是服务端。
- 正向:代理客户端,服务端无法知道实际请求的客户端
- 反向:代理服务端,客户端无法知道实际响应的服务端。如:CDN,负载均衡,varnish缓存
补充一张比较直观的图:
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/25/magento-access-varnish/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论