Base di conoscenze

1 000 FAQ, 500 tutorial e video esplicativi. Qui ci sono delle soluzioni!

Utilizzare Varnish su un server Cloud

Aggiornamento 01/09/2026

Questa guida presenta diversi esempi di utilizzo di Varnish su Server Cloud Infomaniak.

 

Introduzione

 

Configurazione di Varnish

Una volta installato, la configurazione di Varnish si basa su regole precise di memorizzazione nella cache e di svuotamento della cache. Assicurati di limitare l'accesso per evitare che entità non autorizzate possano svuotare la tua cache.

Ecco un esempio di file di configurazione che raccoglie i casi d'uso più frequenti:

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;
    }
}

 

Eliminazione tramite l'interfaccia CLI

Una volta che le regole sono attive, è possibile testare l'eliminazione della cache del sito (ad esempio, "domain.xyz") utilizzando lo strumento 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>

Per invalidare una specifica URL, è sufficiente modificare il percorso della richiesta:

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

Oppure, per avviare l'invalidazione di gruppo delle immagini definite nel 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>

 

Svuotamento della cache da un CMS (PHP)

La gestione della cache può essere effettuata anche dinamicamente tramite il backend. Nella configurazione precedente, è stato aggiunto un controllo sull'intestazione Uncacheable. Il CMS può inviare questa intestazione per forzare Varnish a non memorizzare una risposta.

Ecco come inviare una richiesta di svuotamento della cache tramite 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);
}
?>

Questa FAQ è stata utile?