','

' ); } ?>

Instalar Varnish en servidor Plesk para usarlo con WordPress

A continuación os vamos a explicar de manera lo más sencilla posible como puedes instalar Varnish en un servidor Plesk para que pueda correr perfectamente con tus proyectos WordPress.

Requerimientos :

  • Instalar extension Docker en Plesk.

Usamos el puerto 80 a 32780

Configurar los puertos correctamente.
  • Instalar en Docker la imagen: million12/varnish

Instalación :

Una vez tengamos instalado del docker de Varnish entramos al docker para modificar los ficheros de configuración :

docker ps
docker exec -it XXXXXXXXXX bash
cd /etc/varnish
yum install nano 
mv default.vcl default.ORI
nano default.vcl

Sustituimos XXXXXXXXX por el ID del docker que obtenemos con el comando anterior.

Dentro del fichero default.vcl pegamos el siguiente contenido:

###############################################################################################
### Configuración perfecta para Varnish 4.x+  Joomla, WordPress & otros CMS.     ###
###############################################################################################

######################
#
# ACTUALIZADO EL 25 FEB 2020
#
# Configuración:
#
# 1. Sustituye la ip publica por la de tu servidor.
# 
# 2. El rango del Docker suele ser : 172.17.0.1 si no es este cambiado.
#
# 3. Si tienes una url personalizada para el login de WordPress sustituye  "/editar" en las lines del fichero donde aparezca por la url personalizada que uses. 
#
######################


# VCL compilado para version 4.0 
vcl 4.0;

# Imports
import std;

# Sustituye la ip publica por la de tu servidor.
backend default {
    .host = "PONERIPPUBLICADETUSERVER"; # UPDATE this only if the web server is not on the same machine
    .port = "7080";      # UPDATE 8080 with your web server's (internal) port

#    .connect_timeout = 600s;
#    .first_byte_timeout = 600s;
#    .between_bytes_timeout = 600s;
#    .max_connections = 250;

}

# IP A LAS QUE SE LE PERMITE PURGAR LA CACHE. PONER IP DEL SERVIDOR + RANGO DOCKER

acl purge {
    "localhost";
    "127.0.0.1";
    "172.17.0.1";
    "PONERIPPUBLICADETUSERVER";
}

sub vcl_recv {


# 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);
        }
	if (req.method == "CLEANFULLCACHE") {
                # 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
                ban("req.http.host ~ .*");
    		return (synth(200, "Full cache cleared"));
        }


/*
    # Blocks
    if (req.http.user-agent ~ "^$" && req.http.referer ~ "^$") {
        return (synth(204, "No content"));
    }
    if (req.http.user-agent ~ "(ahrefs|bingbot|domaincrawler|dotbot|mj12bot|semrush)") {
        return (synth(204, "Bot blocked"));
    }
    # If we host multiple domains on a server, here you can list the domains you DO NOT want to cache
    # The first check matches both naked & "www" subdomains. Use the second for non generic subdomains.
#    if (
#        req.http.host ~ "(www\.)?(domain1.com|domain2.org|domain3.net)" ||
#        req.http.host ~ "(subdomain.domain4.tld|othersubdomain.domain5.tld)"
#    ) {
#        return (pass);
#    }
*/

    # LetsEncrypt Certbot passthrough
    if (req.url ~ "^/\.well-known/acme-challenge/") {
        return (pass);
    }

    # Forward client's IP to the backend
    if (req.restarts == 0) {
        if (req.http.X-Real-IP) {
            set req.http.X-Forwarded-For = req.http.X-Real-IP;
        } else if (req.http.X-Forwarded-For) {
            set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
        } else {
            set req.http.X-Forwarded-For = client.ip;
        }
    }

    # httpoxy
    unset req.http.proxy;

    # Normalize the query arguments (but exclude for WordPress' backend)
    if (req.url !~ "wp-admin") {
        set req.url = std.querysort(req.url);
    }

    # Non-RFC2616 or CONNECT which is weird.
    if (
        req.method != "GET" &&
        req.method != "HEAD" &&
        req.method != "PUT" &&
        req.method != "POST" &&
        req.method != "TRACE" &&
        req.method != "OPTIONS" &&
        req.method != "DELETE"
    ) {
        return (pipe);
    }

    # We only deal with GET and HEAD by default
    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    # === URL manipulation ===
    # First remove the Google Analytics added parameters, useless for our backend
    if (req.url ~ "(\?|&)(utm_source|utm_medium|utm_campaign|utm_content|gclid|cx|ie|cof|siteurl)=") {
        set req.url = regsuball(req.url, "&(utm_source|utm_medium|utm_campaign|utm_content|gclid|cx|ie|cof|siteurl)=([A-z0-9_\-\.%25]+)", "");
        set req.url = regsuball(req.url, "\?(utm_source|utm_medium|utm_campaign|utm_content|gclid|cx|ie|cof|siteurl)=([A-z0-9_\-\.%25]+)", "?");
        set req.url = regsub(req.url, "\?&", "?");
        set req.url = regsub(req.url, "\?$", "");
    }

    # Strip hash, server doesn't need it.
    if (req.url ~ "\#") {
        set req.url = regsub(req.url, "\#.*$", "");
    }

    # Strip a trailing ? if it exists
    #if (req.url ~ "\?$") {
    #    set req.url = regsub(req.url, "\?$", "");
    #}

    # === Generic cookie manipulation ===
    # 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.=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "_ga=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "_gat=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "utmctr=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "utmcmd.=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "utmccn.=[^;]+(; )?", "");

    # Remove DoubleClick offensive cookies
    set req.http.Cookie = regsuball(req.http.Cookie, "__gads=[^;]+(; )?", "");

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

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

    # 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=[^;]+(; )?", "");

    # Remove a ";" prefix in the cookie if present
    set req.http.Cookie = regsuball(req.http.Cookie, "^;\s*", "");

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

    # Check for the custom "X-Logged-In" header (used by K2 and other apps) to identify
    # if the visitor is a guest, then unset any cookie (including session cookies) provided
    # it's not a POST request.
    if(req.http.X-Logged-In == "False" && req.method != "POST") {
        unset req.http.Cookie;
    }

    # === DO NOT CACHE ===
    # Don't cache HTTP authorization/authentication pages and pages with certain headers or cookies
    if (
        req.http.Authorization ||
        req.http.Authenticate ||
        req.http.X-Logged-In == "True" ||
        req.http.Cookie ~ "userID" ||
        req.http.Cookie ~ "joomla_[a-zA-Z0-9_]+" ||
        req.http.Cookie ~ "(wordpress_[a-zA-Z0-9_]+|wp-postpass|comment_author_[a-zA-Z0-9_]+|woocommerce_cart_hash|woocommerce_items_in_cart|wp_woocommerce_session_[a-zA-Z0-9]+)"
    ) {
        #set req.http.Cache-Control = "private, max-age=0, no-cache, no-store";
        #set req.http.Expires = "Mon, 01 Jan 2001 00:00:00 GMT";
        #set req.http.Pragma = "no-cache";
        return (pass);
    }

    # Exclude the following paths (e.g. backend admins, user pages or ad URLs that require tracking)
    # In Joomla specifically, you are advised to create specific entry points (URLs) for users to
    # interact with the site (either common user logins or even commenting), e.g. make a menu item
    # to point to a user login page (e.g. /login), including all related functionality such as
    # password reset, email reminder and so on.
    if(
        req.url ~ "^/addons" ||
        req.url ~ "^/administrator" ||
        req.url ~ "^/cart" ||
        req.url ~ "^/checkout" ||
        req.url ~ "^/component/banners" ||
        req.url ~ "^/component/socialconnect" ||
        req.url ~ "^/component/users" ||
        req.url ~ "^/connect" ||
        req.url ~ "^/contact" ||
        req.url ~ "^/login" ||
        req.url ~ "^/editar" ||
        req.url ~ "^/logout" ||
        req.url ~ "^/lost-password" ||
        req.url ~ "^/my-account" ||
        req.url ~ "^/register" ||
        req.url ~ "^/signin" ||
        req.url ~ "^/signup" ||
        req.url ~ "^/wc-api" ||
        req.url ~ "^/wp-admin" ||
        req.url ~ "^/wp-login.php" ||
        req.url ~ "^\?add-to-cart=" ||
        req.url ~ "^\?wc-api="
    ) {
        #set req.http.Cache-Control = "private, max-age=0, no-cache, no-store";
        #set req.http.Expires = "Mon, 01 Jan 2001 00:00:00 GMT";
        #set req.http.Pragma = "no-cache";
        return (pass);
    }

    # Don't cache ajax requests
    if(req.http.X-Requested-With == "XMLHttpRequest" || req.url ~ "nocache") {
        #set req.http.Cache-Control = "private, max-age=0, no-cache, no-store";
        #set req.http.Expires = "Mon, 01 Jan 2001 00:00:00 GMT";
        #set req.http.Pragma = "no-cache";
        return (pass);
    }

    # === STATIC FILES ===
    # Properly handle different encoding types
    if (req.http.Accept-Encoding) {
        if (req.url ~ "\.(jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$") {
            # No point in compressing these
            unset req.http.Accept-Encoding;
        } elseif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
        } elseif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
        } else {
            # unknown algorithm (aka crappy browser)
            unset req.http.Accept-Encoding;
        }
    }

    # Remove all cookies for static files & deliver directly
    if (req.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
        unset req.http.Cookie;
        return (hash);
    }

    return (hash);

}

sub vcl_backend_response {

/*
    # If we host multiple domains on a server, here you can list the domains you DO NOT want to cache
    # The first check matches both naked & "www" subdomains. Use the second for non generic subdomains.
#    if (
#        bereq.http.host ~ "(www\.)?(domain1.com|domain2.org|domain3.net)" ||
#        bereq.http.host ~ "(subdomain.domain4.tld|othersubdomain.domain5.tld)"
#    ) {
#        set beresp.uncacheable = true;
#        return (deliver);
#    }


    #Fix a strange problem: HTTP 301 redirects

    if (beresp.http.Location == "http://" + bereq.http.host + bereq.url) {
    if (bereq.retries > 2) {
      unset beresp.http.Location;
      #set beresp.http.X-Restarts = bereq.retries;
    } else {
      return (retry);
    }
    }


*/

    # Don't cache 50x responses
    if (
        beresp.status == 500 ||
        beresp.status == 502 ||
        beresp.status == 503 ||
        beresp.status == 504
    ) {
        return (abandon);
    }

    # === DO NOT CACHE ===
    # Exclude the following paths (e.g. backend admins, user pages or ad URLs that require tracking)
    # In Joomla specifically, you are advised to create specific entry points (URLs) for users to
    # interact with the site (either common user logins or even commenting), e.g. make a menu item
    # to point to a user login page (e.g. /login), including all related functionality such as
    # password reset, email reminder and so on.
    if(
        bereq.url ~ "^/addons" ||
        bereq.url ~ "^/administrator" ||
        bereq.url ~ "^/cart" ||
        bereq.url ~ "^/checkout" ||
        bereq.url ~ "^/component/banners" ||
        bereq.url ~ "^/component/socialconnect" ||
        bereq.url ~ "^/component/users" ||
        bereq.url ~ "^/connect" ||
        bereq.url ~ "^/contact" ||
        bereq.url ~ "^/login" ||
        bereq.url ~ "^/editar" ||
        bereq.url ~ "^/logout" ||
        bereq.url ~ "^/lost-password" ||
        bereq.url ~ "^/my-account" ||
        bereq.url ~ "^/register" ||
        bereq.url ~ "^/signin" ||
        bereq.url ~ "^/signup" ||
        bereq.url ~ "^/wc-api" ||
        bereq.url ~ "^/wp-admin" ||
        bereq.url ~ "^/wp-login.php" ||
        bereq.url ~ "^\?add-to-cart=" ||
        bereq.url ~ "^\?wc-api="
    ) {
        #set beresp.http.Cache-Control = "private, max-age=0, no-cache, no-store";
        #set beresp.http.Expires = "Mon, 01 Jan 2001 00:00:00 GMT";
        #set beresp.http.Pragma = "no-cache";
        set beresp.uncacheable = true;
        return (deliver);
    }

    # Don't cache HTTP authorization/authentication pages and pages with certain headers or cookies
    if (
        bereq.http.Authorization ||
        bereq.http.Authenticate ||
        bereq.http.X-Logged-In == "True" ||
        bereq.http.Cookie ~ "userID" ||
        bereq.http.Cookie ~ "joomla_[a-zA-Z0-9_]+" ||
        bereq.http.Cookie ~ "(wordpress_[a-zA-Z0-9_]+|wp-postpass|comment_author_[a-zA-Z0-9_]+|woocommerce_cart_hash|woocommerce_items_in_cart|wp_woocommerce_session_[a-zA-Z0-9]+)"
    ) {
        #set beresp.http.Cache-Control = "private, max-age=0, no-cache, no-store";
        #set beresp.http.Expires = "Mon, 01 Jan 2001 00:00:00 GMT";
        #set beresp.http.Pragma = "no-cache";
        set beresp.uncacheable = true;
        return (deliver);
    }

    # Don't cache ajax requests
    if(beresp.http.X-Requested-With == "XMLHttpRequest" || bereq.url ~ "nocache") {
        #set beresp.http.Cache-Control = "private, max-age=0, no-cache, no-store";
        #set beresp.http.Expires = "Mon, 01 Jan 2001 00:00:00 GMT";
        #set beresp.http.Pragma = "no-cache";
        set beresp.uncacheable = true;
        return (deliver);
    }

    # Don't cache backend response to posted requests
    if (bereq.method == "POST") {
        set beresp.uncacheable = true;
        return (deliver);
    }

    # Ok, we're cool & ready to cache things
    # so let's clean up some headers and cookies
    # to maximize caching.

    # Check for the custom "X-Logged-In" header to identify if the visitor is a guest,
    # then unset any cookie (including session cookies) provided it's not a POST request.
    if(beresp.http.X-Logged-In == "False" && bereq.method != "POST") {
        unset beresp.http.Set-Cookie;
    }

    # Unset the "pragma" header (suggested)
    unset beresp.http.Pragma;

    # Unset the "vary" header (suggested)
    unset beresp.http.Vary;

    # Unset the "etag" header (optional)
    #unset beresp.http.etag;

    # Allow stale content, in case the backend goes down
    set beresp.grace = 24h;

    # Enforce your own cache TTL (optional)
    #set beresp.ttl = 180s;

    # Modify "expires" header - https://www.varnish-cache.org/trac/wiki/VCLExampleSetExpires (optional)
    #set beresp.http.Expires = "" + (now + beresp.ttl);

    # If your backend server does not set the right caching headers for static assets,
    # you can set them below (uncomment first and change 604800 - which 1 week - to whatever you
    # want (in seconds)
    #if (bereq.url ~ "\.(ico|jpg|jpeg|gif|png|bmp|webp|tiff|svg|svgz|pdf|mp3|flac|ogg|mid|midi|wav|mp4|webm|mkv|ogv|wmv|eot|otf|woff|ttf|rss|atom|zip|7z|tgz|gz|rar|bz2|tar|exe|doc|docx|xls|xlsx|ppt|pptx|rtf|odt|ods|odp)(\?[a-zA-Z0-9=]+)$") {
    #    set beresp.http.Cache-Control = "public, max-age=604800";
    #}

    if (bereq.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
        unset beresp.http.set-cookie;
        set beresp.do_stream = true;
    }

    # We have content to cache, but it's got no-cache or other Cache-Control values sent
    # So let's reset it to our main caching time (180s as used in this example configuration)
    # The additional parameters specified (stale-while-revalidate & stale-if-error) are used
    # by modern browsers to better control caching. Set these to twice & four times your main
    # cache time respectively.
    # This final setting will normalize cache-control headers for CMSs like Joomla
    # which set max-age=0 even when the CMS' cache is enabled.
    if (beresp.http.Cache-Control !~ "max-age" || beresp.http.Cache-Control ~ "max-age=0") {
        set beresp.http.Cache-Control = "public, max-age=180, stale-while-revalidate=360, stale-if-error=43200";
    }

    # Optionally set a larger TTL for pages with less than 180s of cache TTL
    #if (beresp.ttl < 180s) {
    #    set beresp.http.Cache-Control = "public, max-age=180, stale-while-revalidate=360, stale-if-error=43200";
    #}

    return (deliver);

}

sub vcl_deliver {

/*
    # Send a special header for excluded domains only
    # The if statement can be identical to the ones in the vcl_recv() and vcl_fetch() functions above
#    if (
#        req.http.host ~ "(www\.)?(domain1.com|domain2.org|domain3.net)" ||
#        req.http.host ~ "(subdomain.domain4.tld|othersubdomain.domain5.tld)"
#    ) {
#        set resp.http.X-Domain-Status = "EXCLUDED";
#    }
    # Enforce redirect to HTTPS for specified domains only ( lo he comentado )
#    if (
#        req.http.host ~ "(subdomain.domain4.tld|othersubdomain.domain5.tld)" &&
#        req.http.X-Forwarded-Proto !~ "(?i)https"
#    ) {
#        set resp.http.Location = "https://" + req.http.host + req.url;
#        set resp.status = 302;
#    }
*/
    # Send special headers that indicate the cache status of each web page
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
        set resp.http.X-Cache-Hits = obj.hits;
    } else {
        set resp.http.X-Cache = "MISS";
    }

    return (deliver);

}

Pegamos el contenido de este fichero en el default.vcl del docker de varnish y guardamos los cambios ( Ctrl + x : guardar: YES) y reincidamos el docker desde el gestor o mediante consola.

Configurar parametros para servidor WordPress

Una vez llegados a este punto ya tenemos un docker con Varnish preparado para funcionar con una instalación de WordPress pero deberemos modificar una serie de parámetros para que no tengamos problemas.

El más importante hace referencia a las conexiones seguras pues varnish no funciona si tenemos activado en el servidor plesk las redirecciones ( http a https ) por tanto lo primero es desactivarlas desde el servidor.

Ahora abrimoos el fichero wpconfig.php de WordPress y añadimos «al principio» las siguientes líneas :

//Begin Really Simple SSL Load balancing fix
$server_opts = array("HTTP_CLOUDFRONT_FORWARDED_PROTO" => "https", "HTTP_CF_VISITOR"=>"https", "HTTP_X_FORWARDED_PROTO"=>"https", "HTTP_X_FORWARDED_SSL"=>"on", "HTTP_X_FORWARDED_SSL"=>"1");
foreach( $server_opts as $option => $value ) {
  if ((isset($_ENV["HTTPS"]) && ( "on" == $_ENV["HTTPS"] )) || (isset( $_SERVER[ $option ] ) && ( strpos( $_SERVER[ $option ], $value ) !== false )) ) {
    $_SERVER[ "HTTPS" ] = "on";
  }
}
//END Really Simple SSL

*Con esto conseguimos que los plugins de WordPress que lo necesiten lean la ip real de los visitantes en vez de la del docker de Varnish. Es algo muy importante para los logs de acceso o si utilizamos plugins para limitar los intentos de login.

En la última linea del fichero añadimos el siguiente comando para evitar errores «301 Infinite Loops» :

/** Force HTTPS **/
$_SERVER['HTTPS'] = "on";

*Es muy importante hacerlo así y no de otra manera pues si no se hace así el servidor Varnish nos puede dar fallos de acceso por tener demasiadas redirecciones concurrentes. Si lo haces así no tendrás ningún problema. Este problema lo tuve durante un par de semanas hasta que descubrí que haciendolo de este modo todo iba como la seda.

Redireccionar espacio Web a Docker Varnish

Llegados a este punto ya tenemos Varnish configurado y preparado para WordPress, también tenemos WordPress configurado para poder funcionar con https y Varnish y leer las direcciones Ip reales, por tanto lo que deberemos hacer es crear una regla del proxy docker en el espacio de la web para que las visitas entren a través de Varnish.

  • Entramos en Reglas de proxy de Docker y Añadimos la regla.

Instalamos plugin para limpiar Cache en WordPress

Llegados a este punto ya tenemos WordPress funcionando perfectamente con Varnish , algo que podrás probar desde la consola de un equipo cliente accediendo a la web con el comando :

curl -I jorgedihe.com

Si lo ejecutas varias veces veras en la cabecera como Varnish «HIT» lo cual te hace ver que te servido una página cacheada desde Varnish.

Para limpiar la cache podremos sencillamente reiniciar el Docker y se limpiará completamente pero otra opción es instalar un plugin que lo que hará es borrar la cache de la web cuando se modifique un artículo de WordPress.

Para instalar el plugin creamos el fichero clearcache.php dentro de wp-content/plugins con el siguiente contenido :

<?php

/**
 * Varnish Cache Cleaner.
 *
 * @package   Cache_Cleaner
 * @author    Eni Sinanaj <[email protected]>
 * @link      https://enisinanal.com
 * @copyright 2013-2019 Eni Sinanaj
 *
 * @wordpress-plugin
 * Plugin Name: CacheCleaner
 * Plugin URI: http://enisinanaj.com/cachecleaner
 * Description: Clean FastCGI cache for NGinX and eventually Varnish Cache server 
 * Version: 1.0
 * Author: Eni Sinanaj
 * Author URI: http://enisinanaj.com
 */

// load basic path to the plugin
define( 'CCLEANER_BASE', plugin_basename( __FILE__ ) ); // plugin base as used by WordPress to identify it
define( 'CCLEANER_BASE_PATH', plugin_dir_path( __FILE__ ) );
define( 'CCLEANER_BASE_URL', plugin_dir_url( __FILE__ ) );
define( 'CCLEANER_BASE_DIR', dirname( CCLEANER_BASE ) ); // directory of the plugin without any paths
// general and global slug, e.g. to store options in WP
define( 'CCLEANER_SLUG', 'wp-cache-cleaner' );
define( 'CCLEANER_VERSION', '1.0' );

/*----------------------------------------------------------------------------*
 * Autoloading, modules and functions
 *----------------------------------------------------------------------------*/

// load public functions (might be used by modules, other plugins or theme)
//require_once CCLEANER_BASE_PATH . 'settings_page.php';

add_action( 'save_post', 'clean_cache' );
function clean_cache($post_ID = null, $post = null, $update = null) {
	
	$headers = array (
        "Host: ".$_SERVER['HTTP_HOST']."", // IMPORTANT
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3",
        "Accept-Encoding: gzip,deflate,sdch",
        "Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4",
        "Cache-Control: max-age=0",
        "Connection: keep-alive",
    );
	
	$curlOptionList = array(
			CURLOPT_URL                     => 'http://172.17.0.2,
			CURLOPT_HTTPHEADER              => $headers,
			CURLOPT_CUSTOMREQUEST           => "CLEANFULLCACHE",
			CURLOPT_VERBOSE                 => true,
			CURLOPT_RETURNTRANSFER          => true,
			CURLOPT_NOBODY                  => true,
			CURLOPT_CONNECTTIMEOUT_MS       => 2000,
	);
	
    $curlHandler = curl_init();
    curl_setopt_array( $curlHandler, $curlOptionList );
    curl_exec( $curlHandler );
    curl_close( $curlHandler );
}

*La IP 172.17.02 por la IP es la que tenga el contenedor Docker con Varnish. Si tienes Plesk Onyx lo normal es que sea esa pero verifícalo viendo que ip tienen los docker.

Para ver la ip del Docker desde la consola del servidor :

docker inspect <container id> | grep "IPAddress"

Ver los Logs de Varnish

Si entramos al docker podemos ver los logs con el siguiente comando :

varnishncsa

Si lo quieres ver con la IP Real de los visitantes lo puedes hacer así :


varnishncsa -F '%{X-Forwarded-For}i %l %u %t "%r" %s %b "%{Referer}i" "%{User-agent}i"'

Si te ha sido de utilidad este artículo.

Si este artículo te ha resultado de ayuda puedes colaborar mediante una donación para el mantenimiento del blog.