Base de conocimientos

1 000 FAQ, 500 tutoriales y vídeos explicativos. ¡Aquí sólo hay soluciones!

Utilizar Varnish en un Servidor Cloud

Actualización 01/09/2026

Esta guía presenta varios ejemplos de uso de Varnish en Servidor Cloud de Infomaniak.

 

Introducción

 

Configuración de Varnish

Una vez instalado, la configuración de Varnish se basa en reglas precisas de almacenamiento en caché y de limpieza de la caché. Asegúrese de restringir el acceso para evitar que entidades no autorizadas puedan vaciar su caché.

Aquí tiene un ejemplo de archivo de configuración que incluye los casos de uso más frecuentes:

vcl 4.0;

# Default backend configuration
backend default {
    .host = "127.0.0.80";  # Backend IP address
    .port = "80";           # Backend port
}

# Access Control List (ACL) for purge authorization
acl purge {
    "localhost";            # Local access
    "1.2.3.4";              # Trusted home IP
    "42.42.42.0"/24;        # Trusted company range
    ! "42.42.42.7";         # Specific IP exclusion (e.g., problematic user)
}

# Handle incoming requests
sub vcl_recv {
    # Handle PURGE requests
    if (req.method == "PURGE") {
        # Check if client IP is authorized
        if (!client.ip ~ purge) {
            return (synth(405, "IP not authorized for PURGE requests."));
        }
        return (purge);
    }

    # Custom PURGEALL for image directory
    if (req.method == "PURGEALL" && req.url == "/images") {
        if (!client.ip ~ purge) {
            return (synth(405, "IP not authorized for PURGEALL requests."));
        }
        # Invalidate all image-related objects in cache
        ban("req.url ~ \.(jpg|png|gif|svg)$");
        return (synth(200, "Images purged."));
    }

    # Bypass cache for authorized requests (e.g., admin panels)
    if (req.http.Authorization) {
        return (pass);
    }
}

# Handle backend responses before caching
sub vcl_backend_response {
    # Set TTL for images to 1 day
    if (beresp.http.content-type ~ "image") {
        set beresp.ttl = 1d;
    }

    # Respect backend's "uncacheable" instruction
    if (beresp.http.uncacheable) {
        set beresp.uncacheable = true;
    }
}

 

Purgado a través de la interfaz de línea de comandos

Una vez que sus reglas estén activas, puede probar el purgado de su sitio (por ejemplo, "domain.xyz") utilizando la herramienta curl:

# Purge the homepage
$ curl -X PURGE {{URL_5}}

# Expected Varnish response
<!DOCTYPE html>
<html>
<head>
    <title>200 Purged</title>
</head>
<body>
    <h1>Success 200: Purge completed</h1>
    <p>The page has been successfully purged.</p>
    <h3>Guru Meditation:</h3>
    <p>XID: 2</p>
    <hr>
    <p>Varnish Cache Server</p>
</body>
</html>

Para eliminar una URL específica, simplemente modifique la ruta de la solicitud:

# Purge a specific file
$ curl -X PURGE {{URL_6}}

# Expected Varnish response
<!DOCTYPE html>
<html>
<head>
    <title>200 Purged</title>
</head>
<body>
    <h1>Success 200: Purge completed</h1>
    <p>The file has been successfully purged.</p>
    <h3>Guru Meditation:</h3>
    <p>XID: 4</p>
    <hr>
    <p>Varnish Cache Server</p>
</body>
</html>

O para iniciar la eliminación masiva de las imágenes definidas en el VCL:

# Execute PURGEALL for images
$ curl -X PURGEALL {{URL_7}}

# Expected Varnish response
<!DOCTYPE html>
<html>
<head>
    <title>200 Purged images</title>
</head>
<body>
    <h1>Success 200: Images purged</h1>
    <p>All images have been successfully purged.</p>
    <h3>Guru Meditation:</h3>
    <p>XID: 32770</p>
    <hr>
    <p>Varnish Cache Server</p>
</body>
</html>

 

Purgado desde un CMS (PHP)

La gestión de la caché también se puede realizar de forma dinámica a través de su panel de administración. En la configuración anterior, se añadió un control sobre la cabecera Uncacheable. Su CMS puede enviar esta cabecera para obligar a Varnish a no almacenar una respuesta.

A continuación, se muestra cómo enviar una solicitud de purga programática en PHP:

<?php
// Initialize cURL for a specific URL
if ($curl = curl_init("{{URL_8}}")) {
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "PURGE",
        CURLOPT_HTTPHEADER => [
            "Host: {$_SERVER['HTTP_HOST']}" // Match the target host
        ]
    ]);

    curl_exec($curl);
    
    // Check if the purge was successful (HTTP 200)
    if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200) {
        echo "Cache purged!";
    }
    curl_close($curl);
}
?>

¿Le ha sido útil esta FAQ?