Base de conhecimento

1000 perguntas frequentes, 500 tutoriais e vídeos explicativos. Aqui, você encontra apenas soluções!

Usar o Varnish em um Servidor Cloud

Atualização 01/09/2026

Este guia apresenta vários exemplos de utilização do Varnish em Servidor Cloud Infomaniak.

 

Introdução

 

Configuração do Varnish

Após a instalação, a configuração do Varnish baseia-se em regras precisas de armazenamento em cache e limpeza do cache. Certifique-se de restringir o acesso para evitar que entidades não autorizadas possam limpar o seu cache.

Aqui está um exemplo de um arquivo de configuração que reúne os casos de uso mais frequentes:

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

 

Limpeza via interface de linha de comando

Assim que as suas regras estiverem ativas, pode testar a limpeza do seu site (ex: "domain.xyz") utilizando a ferramenta 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 limpar uma URL específica, basta modificar o caminho da solicitação:

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

Ou para iniciar a limpeza em lote das imagens definidas no 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>

 

Limpeza a partir de um CMS (PHP)

O gerenciamento do cache também pode ser feito dinamicamente através do seu painel de controle. Na configuração anterior, foi adicionada uma verificação no cabeçalho Uncacheable. O seu CMS pode enviar este cabeçalho para forçar o Varnish a não armazenar uma resposta.

Veja como enviar uma solicitação de limpeza programática em 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);
}
?>

Esta seção de perguntas frequentes foi útil?