Base de conocimientos

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

Usar Varnish en Servidor Cloud

Actualización 10/03/2026

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

 

Preámbulo

 

Configuración de Varnish

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

Aquí hay un ejemplo de archivo de configuración que agrupa 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;
    }
}

 

Eliminación a través de la interfaz CLI

Tan pronto como sus reglas estén activas, puede probar la eliminación de su sitio (por ejemplo, "domain.xyz") utilizando la herramienta curl:

# Purge the homepage
$ curl -X PURGE https://domain.xyz/

# 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 https://domain.xyz/some_path/some_file.html

# 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 activar la eliminación grupal de imágenes definida en el VCL:

# Execute PURGEALL for images
$ curl -X PURGEALL https://domain.xyz/images

# 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>

 

Eliminación desde un CMS (PHP)

La gestión de la caché también puede realizarse dinámicamente a través de su backend. En la configuración anterior, hemos añadido un control sobre la cabecera Uncacheable. Su CMS puede enviar esta cabecera para forzar a Varnish a no almacenar una respuesta.

Así es como enviar una solicitud de eliminación programática en PHP:

<?php
// Initialize cURL for a specific URL
if ($curl = curl_init("http://127.0.0.1/some_url")) {
    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?