如何为WordPress配置Varnish 4

时间:2020-01-09 10:39:02  来源:igfitidea点击:

如何使用称为Varnish的反向代理缓存来加快WordPress网站的速度。
在本教程中,我们将设置一个缓存服务器,以显着增加站点可以接收的流量,同时减少Web服务器的工作量。

为什么PHP需要缓存

PHP被称为中断语言。简单来说,这意味着它没有预先编译。必须中断代码,编译成计算机可以理解的内容,然后最终将输出推送给用户,这在计算上被认为是昂贵的。所有这些工作意味着Web服务器(例如Apache 2)需要大量资源来提供内容。

这样做的影响是无需增加CPU或者RAM即可服务的用户数量明显减少。

PHP引入了许多有助于解决此问题的功能。较早的功能之一是缓存请求器在请求页面时生成的字节码。不必每次都重新解释PHP文件并将其转换为字节码,PHP可以简单地保存和重用现有的字节码。

随着PHP 7的引入,我们看到了许多重大变化,这些变化显着提高了PHP的性能。

什么是Varnish

Varnish是反向代理缓存。反向代理仅意味着对Web服务器的所有请求在进入Web服务器之前都会通过它进行传输,并且所有响应都将通过代理流回到最终用户。这使Varnish可以监视所有流量并存储内容的预编译静态版本。

与在服务之前必须先编译代码相比,提供静态内容的速度大大加快,并且占用的资源更少。

安装Varnish和配置服务

可以从Ubuntu的官方存储库直接安装Varnish。只要我们至少运行16.04,可用的版本将是4. 默认情况下,Varnish将在端口8080上运行。可以找到,因为我们可能会将缓存服务器置于负载平衡器的后面,监听端口80。与配置不匹配,流量直接流向服务器,我们需要调整设置以使Varnish监听端口80。

安装Varnish

要安装Varnish,请运行以下命令。

sudo apt install varnish -y

配置Varnish以侦听端口80(可选)

要将Varnish配置为侦听端口80,请执行以下操作:

  • 为Varnish服务配置创建目录。
sudo mkdir /etc/systemd/system/varnish.service.d
  • 创建新的服务文件。
sudo touch /etc/systemd/system/varnish.service.d/customexec.conf
  • 在文本编辑器(例如VI)中打开文件。
sudo vi /etc/systemd/system/varnish.service.d/customexec.conf
  • 添加以下行。
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
  • 我们将缓存设置为驻留在RAM(-s malloc)中,并占用256 MB的空间。对于具有1 GB内存的服务器,这是一个不错的设置。

WordPress的上光配置

  • 备份现有的vcl文件。
sudo mv /etc/varnish/default.vcl /etc/varnish/default.vcl.bacup
  • 创建一个新的VCL文件。
sudo touch /etc/varnish/default.vcl
  • 在文本编辑器中打开文件。
sudo vi /etc/varnish/default.vcl
  • 将配置版本设置为4.0
# Marker to tell the VCL compiler that this VCL has been adapted to the
# new 4.0 format.
vcl 4.0;
  • 例如,将后端服务器添加到托管站点的Apache 2 Web服务器。
# Default backend definition. Set this to point to your content server.
backend default {
    .host = "10.0.0.10";
    .port = "80";
    .connect_timeout = 600s;
    .first_byte_timeout = 600s;
    .between_bytes_timeout = 600s;
    .max_connections = 800;
}
  • 仅允许从本地主机或者WordPress主机清除缓存。
# Only allow purging from specific IPs
acl purge {
    "localhost";
    "127.0.0.1";
    "10.0.0.10";
}
  • 设置从HTTP客户端(Web浏览器)收到的请求的规则。我们需要防止将敏感内容(管理页面访问权限)或者可能损坏的内容(Google Analytics(分析))缓存。
# This function is used when a request is send by a HTTP client (Browser) 
sub vcl_recv {
        # Normalize the header, remove the port (in case you're testing this on various TCP ports)
        set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");

        # Allow purging from ACL
        if (req.method == "PURGE") {
                # If not allowed then a error 405 is returned
                if (!client.ip ~ purge) {
                        return(synth(405, "This IP is not allowed to send PURGE requests."));
                }
                # If allowed, do a cache_lookup -> vlc_hit() or vlc_miss()
                return (purge);
        }

        # Post requests will not be cached
        if (req.http.Authorization || req.method == "POST") {
                return (pass);
        }

        # --- WordPress specific configuration

        # Did not cache the RSS feed
        if (req.url ~ "/feed") {
                return (pass);
        }

        # Blitz hack
        if (req.url ~ "/mu-.*") {
                return (pass);
        }

        # Did not cache the admin and login pages
        if (req.url ~ "/wp-(login|admin)") {
                return (pass);
        }

        # Remove the "has_js" cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");

        # Remove any Google Analytics based cookies
        set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");

        # Remove the Quant Capital cookies (added by some plugin, all __qca)
        set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");

        # Remove the wp-settings-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-1=[^;]+(; )?", "");

        # Remove the wp-settings-time-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-time-1=[^;]+(; )?", "");

        # Remove the wp test cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wordpress_test_cookie=[^;]+(; )?", "");

        # Are there cookies left with only spaces or that are empty?
        if (req.http.cookie ~ "^ *$") {
                    unset req.http.cookie;
        }

        # Cache the following files extensions 
        if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
                unset req.http.cookie;
        }

        # Normalize Accept-Encoding header and compression
        # https://www.varnish-cache.org/docs/3.0/tutorial/vary.html
        if (req.http.Accept-Encoding) {
                # Do no compress compressed files...
                if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
                                unset req.http.Accept-Encoding;
                } elsif (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;
                }
        }

        # Check the cookies for wordpress-specific items
        if (req.http.Cookie ~ "wordpress_" || req.http.Cookie ~ "comment_") {
                return (pass);
        }
        if (!req.http.cookie) {
                unset req.http.cookie;
        }

        # --- End of WordPress specific configuration

        # Do not cache HTTP authentication and HTTP Cookie
        if (req.http.Authorization || req.http.Cookie) {
                # Not cacheable by default
                return (pass);
        }

        # Cache all others requests
        return (hash);
}
  • 添加vcl_pipe和vcl_pass指令。
sub vcl_pipe {
        return (pipe);
}

sub vcl_pass {
        return (fetch);
}
  • 将可缓存的项目映射到哈希以快速查找。
# The data on which the hashing will take place
sub vcl_hash {
        hash_data(req.url);
        if (req.http.host) {
             hash_data(req.http.host);
        } else {
             hash_data(server.ip);
        }

        # If the client supports compression, keep that in a different cache
        if (req.http.Accept-Encoding) {
             hash_data(req.http.Accept-Encoding);
        }

        return (lookup);
}
  • 从后端服务器发送的响应中剥离信息。我们也可以选择在此处添加新的标题和其他信息。
# This function is used when a request is sent by our backend (Nginx server)
sub vcl_backend_response {
        # Remove some headers we never want to see
        unset beresp.http.Server;
        unset beresp.http.X-Powered-By;

        # For static content strip all backend cookies
        if (bereq.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico") {
                unset beresp.http.cookie;
        }

        # Only allow cookies to be set if we're in admin area
        if (beresp.http.Set-Cookie && bereq.url !~ "^/wp-(login|admin)") {
                unset beresp.http.Set-Cookie;
        }

        # don't cache response to posted requests or those with basic auth
        if ( bereq.method == "POST" || bereq.http.Authorization ) {
                set beresp.uncacheable = true;
                set beresp.ttl = 120s;
                return (deliver);
        }

        # don't cache search results
        if ( bereq.url ~ "\?s=" ){
                set beresp.uncacheable = true;
                set beresp.ttl = 120s;
                return (deliver);
        }

        # only cache status ok
        if ( beresp.status != 200 ) {
                set beresp.uncacheable = true;
                set beresp.ttl = 120s;
                return (deliver);
        }

        # A TTL of 24h
        set beresp.ttl = 24h;
        # Define the default grace period to serve cached content
        set beresp.grace = 30s;

        return (deliver);
}
  • 将其他信息添加到响应头。例如,我们可以添加是否从缓存中返回了特定的URL。这有助于从客户端进行调试。
# The routine when we deliver the HTTP request to the user
# Last chance to modify headers that are sent to the client
sub vcl_deliver {
        if (obj.hits > 0) {
                set resp.http.X-Cache = "cached";
        } else {
                set resp.http.x-Cache = "uncached";
        }

        # Remove some headers: PHP version
        unset resp.http.X-Powered-By;

        # Remove some headers: Apache version & OS
        unset resp.http.Server;

        # Remove some heanders: Varnish
        unset resp.http.Via;
        unset resp.http.X-Varnish;

        return (deliver);
}
  • 添加选项。
sub vcl_init {
        return (ok);
}

sub vcl_fini {
        return (ok);
}
  • 保存更改并退出文本编辑器。

完成后,配置文件应类似于以下示例。

#
# This is an example VCL file for Varnish.
#
# It does not do anything by default, delegating control to the
# builtin VCL. The builtin VCL is called when there is no explicit
# return statement.
#
# See the VCL chapters in the Users Guide at https://www.varnish-cache.org/docs/
# and https://www.varnish-cache.org/trac/wiki/VCLExamples for more examples.

# Marker to tell the VCL compiler that this VCL has been adapted to the
# new 4.0 format.
vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend default {
    .host = "10.0.0.10";
    .port = "80";
    .connect_timeout = 600s;
    .first_byte_timeout = 600s;
    .between_bytes_timeout = 600s;
    .max_connections = 800;
}

# Only allow purging from specific IPs
acl purge {
    "localhost";
    "127.0.0.1";
    "10.0.0.10";
}

# This function is used when a request is send by a HTTP client (Browser) 
sub vcl_recv {
        # Normalize the header, remove the port (in case you're testing this on various TCP ports)
        set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");

        # Allow purging from ACL
        if (req.method == "PURGE") {
                # If not allowed then a error 405 is returned
                if (!client.ip ~ purge) {
                        return(synth(405, "This IP is not allowed to send PURGE requests."));
                }
                # If allowed, do a cache_lookup -> vlc_hit() or vlc_miss()
                return (purge);
        }

        # Post requests will not be cached
        if (req.http.Authorization || req.method == "POST") {
                return (pass);
        }

        # --- WordPress specific configuration

        # Did not cache the RSS feed
        if (req.url ~ "/feed") {
                return (pass);
        }

        # Blitz hack
        if (req.url ~ "/mu-.*") {
                return (pass);
        }

        # Did not cache the admin and login pages
        if (req.url ~ "/wp-(login|admin)") {
                return (pass);
        }

        # Remove the "has_js" cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");

        # Remove any Google Analytics based cookies
        set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");

        # Remove the Quant Capital cookies (added by some plugin, all __qca)
        set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");

        # Remove the wp-settings-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-1=[^;]+(; )?", "");

        # Remove the wp-settings-time-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-time-1=[^;]+(; )?", "");

        # Remove the wp test cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wordpress_test_cookie=[^;]+(; )?", "");

        # Are there cookies left with only spaces or that are empty?
        if (req.http.cookie ~ "^ *$") {
                    unset req.http.cookie;
        }

        # Cache the following files extensions 
        if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
                unset req.http.cookie;
        }

        # Normalize Accept-Encoding header and compression
        # https://www.varnish-cache.org/docs/3.0/tutorial/vary.html
        if (req.http.Accept-Encoding) {
                # Do no compress compressed files...
                if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
                                unset req.http.Accept-Encoding;
                } elsif (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;
                }
        }

        # Check the cookies for wordpress-specific items
        if (req.http.Cookie ~ "wordpress_" || req.http.Cookie ~ "comment_") {
                return (pass);
        }
        if (!req.http.cookie) {
                unset req.http.cookie;
        }

        # --- End of WordPress specific configuration

        # Do not cache HTTP authentication and HTTP Cookie
        if (req.http.Authorization || req.http.Cookie) {
                # Not cacheable by default
                return (pass);
        }

        # Cache all others requests
        return (hash);
}

sub vcl_pipe {
        return (pipe);
}

sub vcl_pass {
        return (fetch);
}

# The data on which the hashing will take place
sub vcl_hash {
        hash_data(req.url);
        if (req.http.host) {
             hash_data(req.http.host);
        } else {
             hash_data(server.ip);
        }

        # If the client supports compression, keep that in a different cache
        if (req.http.Accept-Encoding) {
             hash_data(req.http.Accept-Encoding);
        }

        return (lookup);
}

# This function is used when a request is sent by our backend (Nginx server)
sub vcl_backend_response {
        # Remove some headers we never want to see
        unset beresp.http.Server;
        unset beresp.http.X-Powered-By;

        # For static content strip all backend cookies
        if (bereq.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico") {
                unset beresp.http.cookie;
        }

        # Only allow cookies to be set if we're in admin area
        if (beresp.http.Set-Cookie && bereq.url !~ "^/wp-(login|admin)") {
                unset beresp.http.Set-Cookie;
        }

        # don't cache response to posted requests or those with basic auth
        if ( bereq.method == "POST" || bereq.http.Authorization ) {
                set beresp.uncacheable = true;
                set beresp.ttl = 120s;
                return (deliver);
        }

        # don't cache search results
        if ( bereq.url ~ "\?s=" ){
                set beresp.uncacheable = true;
                set beresp.ttl = 120s;
                return (deliver);
        }

        # only cache status ok
        if ( beresp.status != 200 ) {
                set beresp.uncacheable = true;
                set beresp.ttl = 120s;
                return (deliver);
        }

        # A TTL of 24h
        set beresp.ttl = 24h;
        # Define the default grace period to serve cached content
        set beresp.grace = 30s;

        return (deliver);
}

# The routine when we deliver the HTTP request to the user
# Last chance to modify headers that are sent to the client
sub vcl_deliver {
        if (obj.hits > 0) {
                set resp.http.X-Cache = "cached";
        } else {
                set resp.http.x-Cache = "uncached";
        }

        # Remove some headers: PHP version
        unset resp.http.X-Powered-By;

        # Remove some headers: Apache version & OS
        unset resp.http.Server;

        # Remove some heanders: Varnish
        unset resp.http.Via;
        unset resp.http.X-Varnish;

        return (deliver);
}

sub vcl_init {
        return (ok);
}

sub vcl_fini {
        return (ok);
}

验证配置

在重新启动Varnish以应用新设置之前,一个好的做法是验证配置文件的语法。如果要使用无效的配置文件重新启动Varnish服务,则会使缓存服务器脱机。为了省去一些麻烦,请每次测试更改。

要测试我们的配置文件,请运行以下命令。

varnishd -C -f /etc/varnish/default.vcl

重新启动Varnish以应用我们的设置

我们已经创建了配置文件,并对其进行了语法错误测试。现在,我们终于可以重新启动服务以应用我们的新设置。

  • 重新启动清漆。
sudo systemctl restart varnish.service
  • 通过查看服务状态,验证Varnish是否已重新启动而没有错误。
sudo systemctl status varnish.service