« Ton site est dangereux, je ne clique pas »
Tu envoies enfin le lien à un ami : http://51.210.34.12. Une minute plus tard, il répond : « Mon navigateur dit Non sécurisé, et c'est quoi cette adresse en chiffres ? Je ne clique pas. » Il a raison de se méfier. Sans HTTPS, c'est-à-dire sans chiffrement, tout ce qui circule entre lui et ton serveur voyage en clair. Mots de passe et formulaires sont lisibles par n'importe quel intermédiaire.
Il te faut deux choses. La première est un nom de domaine : un nom lisible comme ton-projet.fr, qui remplace l'adresse en chiffres. La seconde est un certificat : un justificatif délivré par un organisme tiers. Il prouve que ton serveur est bien celui du domaine, et il permet de chiffrer la connexion.
Ce chiffrement s'appelle TLS. HTTPS, c'est le web classique (HTTP) chiffré par TLS : c'est lui qui affiche le cadenas.
Obtenir et renouveler ce certificat est la partie pénible. Caddy, un serveur web (le programme qui répond aux navigateurs), s'en charge tout seul. Il se règle en cinq lignes, et il fait aussi le lien avec PHP-FPM, le cuisinier de la leçon précédente.
Faire pointer ton nom de domaine vers le VPS (DNS)
Le DNS est l'annuaire d'internet : il traduit ton-projet.fr en 51.210.34.12.
Tu le règles chez ton registrar, le site où tu as acheté le domaine (OVH, Gandi, Namecheap…). Crée-y un enregistrement A : une ligne de l'annuaire qui dit « ce nom correspond à cette IP ».
La propagation, c'est le temps que cette ligne soit connue partout. Elle prend de quelques minutes à quelques heures. Vérifie depuis ton laptop avec nslookup ton-projet.fr : tu dois voir ton IP.
Installer Caddy depuis son dépôt apt officiel
Un dépôt apt est un catalogue de paquets tenu par un éditeur. Celui de Caddy est plus récent que le catalogue de la distribution. Les commandes sont celles de la leçon HTTPS de la voie Docker, section « Caddy sur l'hôte » :
# outils pour ajouter un dépôt apt signé
sudo apt update
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
# télécharge la clé de signature, puis l'adresse du dépôt Caddy
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
# autorise apt à les lire
sudo chmod o+r /usr/share/keyrings/caddy-stable-archive-keyring.gpg /etc/apt/sources.list.d/caddy-stable.list
# met à jour la liste, puis installe
sudo apt update
sudo apt install -y caddy
Ici, curl télécharge une clé et un fichier de dépôt, qu'on range sans les exécuter. Rien à voir avec un curl … | bash.
Le paquet installe aussi le service systemd de Caddy (leçon 3) : il tourne déjà, démarre au boot et se relance s'il tombe. Il sert pour l'instant une page d'accueil par défaut.
Laisser Caddy parler à PHP-FPM (le groupe www-data)
PHP-FPM, le cuisinier, reçoit les commandes de Caddy par la socket, le passe-plat de la leçon précédente : un fichier. Un fichier Linux a un propriétaire, un groupe (un ensemble de comptes qui partagent des droits) et des droits. Ici, le propriétaire est www-data, le groupe est www-data, et les droits sont rw-rw---- : lecture et écriture pour eux, rien pour les autres.
Caddy tourne sous son propre compte, caddy, qui n'est ni l'un ni l'autre. La porte du passe-plat lui est fermée. Dans ce cas, le visiteur voit une erreur 502 : Caddy n'a pas pu joindre PHP-FPM. Caddy doit donc entrer dans le groupe www-data.
Bonne nouvelle : le paquet Caddy ajoute lui-même le compte caddy au groupe www-data, qui existe déjà sur Debian et Ubuntu. Vérifie :
id caddy
id caddy liste les groupes du compte caddy. La ligne doit afficher www-data. Sinon (compte créé autrement, ou paquet d'une autre source), ajoute-le à la main :
sudo usermod -aG www-data caddy
sudo systemctl restart caddy
Le restart est nécessaire : un changement de groupe ne s'applique qu'au démarrage du processus.
Caddy sert au monde le contenu d'un dossier de ton serveur. Ton projet est dans /opt/app. Il contient un sous-dossier public/. Symfony y range tout ce que le monde a le droit de voir : la page d'accueil index.php, les images, le CSS. Lequel donnes-tu à Caddy, et que se passe-t-il si tu te trompes ?
Voir la réponse
/opt/app/public, jamais /opt/app. Caddy envoie au visiteur n'importe quel fichier de son dossier : ce sont des fichiers statiques. Avec la racine du projet, https://ton-projet.fr/.git/config et /composer.json répondraient. Et .env.local ne serait protégé que par ses droits de fichier.
Le Caddyfile : dire à Caddy quoi servir, en cinq lignes
Le Caddyfile est le fichier de réglages de Caddy : /etc/caddy/Caddyfile. Chaque bloc décrit un site. Remplace son contenu (sudo nano /etc/caddy/Caddyfile) par :
ton-projet.fr {
root * /opt/app/public
php_fastcgi unix//run/php/php8.3-fpm.sock
file_server
}
ton-projet.fr {ouvre le bloc du site. Ce nom dit à Caddy pour quel domaine demander un certificat : le HTTPS est automatique dès qu'un vrai nom de domaine est écrit.root * /opt/app/public: le dossier servi. Le*veut dire « pour toutes les requêtes ».php_fastcgi unix//run/php/php8.3-fpm.sock: FastCGI est le langage que PHP-FPM comprend pour recevoir ses requêtes. Cette ligne les lui passe par la socket (les deux/aprèsunixsont normaux). Toute URL qui n'est pas un fichier existant part versindex.php, le point d'entrée de Symfony. Adapte8.3siphp -vdonne autre chose.file_server: envoie tels quels les fichiers statiques depublic/. Un fichier statique est un fichier envoyé sans exécuter de code : image, CSS, JavaScript.
Valide la syntaxe, puis recharge sans couper les visiteurs. caddy validate vérifie le fichier sans toucher au serveur, et reload applique la nouvelle configuration.
caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
Si caddy validate affiche en plus Caddyfile input is not formatted, c'est sans gravité : Caddy préfère les tabulations aux espaces. sudo caddy fmt --overwrite /etc/caddy/Caddyfile règle ça. Seul Valid configuration compte.
Le piège central : root pointe sur public/, jamais sur la racine du projet. À la racine se trouvent .git/ (tout ton historique), composer.json et .env.local. Servis comme des fichiers statiques, ils seraient téléchargeables par n'importe qui, sauf si leurs droits le refusent. Ne compte jamais sur un seul verrou.
Ici, .env.local ne serait sauvé que par son chmod 600 : Caddy n'a pas le droit de le lire. Mais .git/ et composer.json sortiraient bel et bien. Dans public/, Symfony ne laisse que index.php et les ressources publiques. Seuls les fichiers .php présents dans ce dossier peuvent s'exécuter : n'y dépose rien d'autre.
Le certificat en quatre temps (Let's Encrypt et ACME)
Au rechargement, Caddy voit un nom de domaine et demande un certificat à Let's Encrypt. C'est un organisme gratuit, dont les certificats sont acceptés par les navigateurs. Leur dialogue suit un protocole nommé ACME : une suite de messages convenue entre Caddy et Let's Encrypt. Il tient en quatre temps.
- Demande : Caddy demande à Let's Encrypt un certificat pour
ton-projet.fr. - Épreuve : Let's Encrypt ne donne pas un certificat à n'importe qui. Il remet à Caddy un jeton (un code à usage unique). Caddy le publie à l'adresse
http://ton-projet.fr/.well-known/acme-challenge/<jeton>. Let's Encrypt vient le lire, en passant par le DNS, sur le port 80. S'il retrouve son jeton, la machine qui répond est bien celle du domaine. - Livraison : le certificat est délivré et installé, et Caddy redirige HTTP vers HTTPS.
- Renouvellement : le certificat dure 90 jours, et Caddy le renouvelle seul bien avant l'expiration.
Deux conditions, donc : le DNS doit déjà pointer vers ton IP, et les ports 80 et 443 doivent être ouverts. Caddy sait prouver le domaine par le port 80 ou par le 443. On laisse les deux ouverts : ufw le fait déjà depuis la leçon 2, et le 80 sert aussi à rediriger vers HTTPS.
L'erreur n°1 : le DNS ne pointe pas encore vers ton IP (propagation en cours), ou les ports 80 et 443 sont fermés. L'épreuve échoue, Caddy écrit l'erreur dans son journal et réessaie, mais aucun certificat n'est délivré. Vérifie DNS et firewall avant de soupçonner Caddy. Trop d'essais ratés à la suite te font bloquer un moment par Let's Encrypt : patiente plutôt que de relancer en boucle.
Vérifier le HTTPS, puis dépanner
Vérifie depuis l'extérieur. curl -I n'affiche que les en-têtes de la réponse : les lignes d'information qui précèdent la page (statut, serveur, date).
curl -I https://ton-projet.fr
# HTTP/2 200
# server: Caddy
HTTP/2 200 veut dire que la page répond (200 = trouvée) sur une connexion chiffrée. server: Caddy indique quel serveur a répondu : c'est bien Caddy. Le cadenas du navigateur confirme le reste : certificat valide, domaine vérifié.
Il manque l'en-tête strict-transport-security (HSTS). Caddy redirige HTTP vers HTTPS, mais n'envoie pas HSTS de lui-même. Cet en-tête ordonne au navigateur de n'utiliser que HTTPS pour ton domaine pendant une durée donnée. Pour l'ajouter, mets d'abord header Strict-Transport-Security "max-age=300" (cinq minutes) dans le bloc du Caddyfile. Une fois sûr de ton coup, passe à max-age=31536000 (un an) : un HSTS mal réglé est difficile à défaire.
Caddy écrit ses journaux dans celui de systemd. sudo journalctl -u caddy -n 20 affiche les 20 dernières lignes du service caddy (-u). Le sudo est nécessaire : sans lui, deploy ne voit pas le journal des services. Ajoute -f pour les suivre en direct.
Un 502 Bad Gateway veut dire que Caddy n'arrive pas à joindre PHP-FPM. Cherche dans le journal permission denied : c'est le groupe de la section précédente. Cherche aussi une socket introuvable : c'est un numéro de version qui ne correspond pas dans le chemin.
À toi : valide, recharge, vérifie
Ton DNS pointe vers le VPS, Caddy est installé, caddy est dans le groupe www-data et le Caddyfile est écrit. Reste à le faire prendre en compte et à regarder le certificat arriver.
Après un déploiement : recharger PHP-FPM
Tu changes une ligne dans un contrôleur, tu rafraîchis la page, et rien ne bouge : PHP-FPM sert encore l'ancien code.
PHP-FPM ne relit pas tes fichiers à chaque visite. Il garde le code déjà traduit en instructions pour la machine (on dit « compilé ») dans la mémoire, grâce à opcache. Par défaut, il vérifie toutes les deux secondes si un fichier a changé.
En production, on coupe souvent cette vérification (opcache.validate_timestamps=0) pour aller plus vite. Plus rien ne prévient alors PHP-FPM d'un nouveau code. Le réflexe sûr, après chaque mise à jour, est de le recharger :
sudo systemctl reload php8.3-fpm
reload relit la configuration et vide la mémoire. Les nouvelles requêtes voient le nouveau code. restart, lui, arrête puis relance tout le service. Le rechargement est quasi instantané. Une requête qui tourne à cet instant précis peut échouer : c'est invisible pour un petit site. Le réglage process_control_timeout existe pour l'éviter, on n'en a pas besoin ici. Le script de déploiement de la leçon suivante utilisera reload.
Nginx + certbot, honnêtement : nginx est un autre serveur web, très répandu, et certbot est l'outil qui obtient les certificats pour lui. Ensemble, ils donnent exactement le même résultat que Caddy. La différence : une configuration plus longue, et deux outils à faire cohabiter. On commence par Caddy, et tu pourras toujours changer.
"Your site is dangerous, I'm not clicking"
You finally send a friend the link: http://51.210.34.12. A minute later, he answers: "My browser says Not secure, and what's this string of digits? I'm not clicking." He's right to be wary. Without HTTPS, meaning without encryption, everything between him and your server travels in the clear. Passwords and forms are readable by any intermediary.
You need two things. The first is a domain name: a readable name like ton-projet.fr, which replaces the string of digits. The second is a certificate: a document issued by a third-party organization. It proves your server really is the one for the domain, and it allows the connection to be encrypted.
This encryption is called TLS. HTTPS is the classic web (HTTP) encrypted by TLS: it's what shows the padlock.
Getting and renewing that certificate is the painful part. Caddy, a web server (the program that answers browsers), handles it by itself. It's set up in five lines, and it also bridges to PHP-FPM, the cook from the previous lesson.
Pointing your domain name at the VPS (DNS)
DNS is the internet's phone book: it translates ton-projet.fr into 51.210.34.12.
You set it up at your registrar, the site where you bought the domain (OVH, Gandi, Namecheap…). Create an A record there: one line of the phone book saying "this name matches this IP".
Propagation is the time it takes for that line to be known everywhere. It takes a few minutes to a few hours. Check from your laptop with nslookup ton-projet.fr: you should see your IP.
Installing Caddy from its official apt repository
An apt repository is a catalogue of packages kept by a publisher. Caddy's is more recent than the distribution's catalogue. The commands are the ones from the HTTPS lesson of the Docker track, "Caddy on the host" section:
# tools to add a signed apt repository
sudo apt update
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
# download the signing key, then the Caddy repository address
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
# let apt read them
sudo chmod o+r /usr/share/keyrings/caddy-stable-archive-keyring.gpg /etc/apt/sources.list.d/caddy-stable.list
# refresh the list, then install
sudo apt update
sudo apt install -y caddy
Here, curl downloads a key and a repository file, which are filed away without being executed. Nothing like a curl … | bash.
The package also installs Caddy's systemd service (lesson 3): it's already running, starts at boot and restarts if it dies. For now it serves a default welcome page.
Letting Caddy talk to PHP-FPM (the www-data group)
PHP-FPM, the cook, receives Caddy's orders through the socket, the serving hatch from the previous lesson: a file. A Linux file has an owner, a group (a set of accounts that share permissions) and permissions. Here, the owner is www-data, the group is www-data, and the permissions are rw-rw----: read and write for them, nothing for anyone else.
Caddy runs under its own account, caddy, which is neither. The serving hatch's door is closed to it. In that case, the visitor sees a 502 error: Caddy couldn't reach PHP-FPM. So Caddy must join the www-data group.
Good news: the Caddy package itself adds the caddy account to the www-data group, which already exists on Debian and Ubuntu. Check:
id caddy
id caddy lists the groups of the caddy account. The line must show www-data. Otherwise (account created another way, or a package from another source), add it by hand:
sudo usermod -aG www-data caddy
sudo systemctl restart caddy
The restart is needed: a group change only applies when the process starts.
Caddy serves the content of one folder of your server to the world. Your project is in /opt/app. It contains a public/ subfolder. Symfony puts there everything the world is allowed to see: the index.php home page, images, CSS. Which one do you give Caddy, and what happens if you get it wrong?
Show the answer
/opt/app/public, never /opt/app. Caddy sends the visitor any file in its folder: these are static files. With the project root, https://ton-projet.fr/.git/config and /composer.json would answer. And .env.local would only be protected by its file permissions.
The Caddyfile: telling Caddy what to serve, in five lines
The Caddyfile is Caddy's settings file: /etc/caddy/Caddyfile. Each block describes a site. Replace its content (sudo nano /etc/caddy/Caddyfile) with:
ton-projet.fr {
root * /opt/app/public
php_fastcgi unix//run/php/php8.3-fpm.sock
file_server
}
ton-projet.fr {opens the site block. This name tells Caddy which domain to request a certificate for: HTTPS is automatic as soon as a real domain name is written.root * /opt/app/public: the folder served. The*means "for all requests".php_fastcgi unix//run/php/php8.3-fpm.sock: FastCGI is the language PHP-FPM understands to receive its requests. This line hands them over through the socket (the two/afterunixare normal). Any URL that isn't an existing file goes toindex.php, Symfony's entry point. Adapt8.3ifphp -vsays otherwise.file_server: sends the static files ofpublic/as they are. A static file is a file sent without running any code: image, CSS, JavaScript.
Validate the syntax, then reload without cutting off visitors. caddy validate checks the file without touching the server, and reload applies the new configuration.
caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
If caddy validate also prints Caddyfile input is not formatted, it's harmless: Caddy prefers tabs to spaces. sudo caddy fmt --overwrite /etc/caddy/Caddyfile fixes it. Only Valid configuration matters.
The central trap: root points to public/, never to the project root. The root holds .git/ (your whole history), composer.json and .env.local. Served as static files, they would be downloadable by anyone, unless their permissions refuse it. Never rely on a single lock.
Here, .env.local would only be saved by its chmod 600: Caddy isn't allowed to read it. But .git/ and composer.json would come out for real. In public/, Symfony leaves only index.php and the public assets. Only .php files present in that folder can run: put nothing else in it.
The certificate in four steps (Let's Encrypt and ACME)
On reload, Caddy sees a domain name and asks Let's Encrypt for a certificate. It's a free authority, whose certificates browsers accept. Their dialogue follows a protocol called ACME: a series of messages agreed between Caddy and Let's Encrypt. It takes four steps.
- Request: Caddy asks Let's Encrypt for a certificate for
ton-projet.fr. - Challenge: Let's Encrypt doesn't give a certificate to just anyone. It hands Caddy a token (a one-time code). Caddy publishes it at
http://ton-projet.fr/.well-known/acme-challenge/<token>. Let's Encrypt comes to read it, through DNS, on port 80. If it finds its token, the machine answering really is the domain's. - Delivery: the certificate is issued and installed, and Caddy redirects HTTP to HTTPS.
- Renewal: the certificate lasts 90 days, and Caddy renews it by itself well before it expires.
Two conditions, then: DNS must already point to your IP, and ports 80 and 443 must be open. Caddy can prove the domain through port 80 or through 443. We leave both open: ufw already does since lesson 2, and port 80 also redirects to HTTPS.
Mistake number 1: DNS doesn't point to your IP yet (propagation in progress), or ports 80 and 443 are closed. The challenge fails, Caddy writes the error to its journal and retries, but no certificate is issued. Check DNS and firewall before suspecting Caddy. Too many failed attempts in a row get you blocked by Let's Encrypt for a while: be patient rather than reloading in a loop.
Checking HTTPS, then troubleshooting
Check from the outside. curl -I only prints the response headers: the information lines that come before the page (status, server, date).
curl -I https://ton-projet.fr
# HTTP/2 200
# server: Caddy
HTTP/2 200 means the page answers (200 = found) over an encrypted connection. server: Caddy tells which server answered: it's Caddy. The browser padlock confirms the rest: valid certificate, verified domain.
The strict-transport-security header (HSTS) is missing. Caddy redirects HTTP to HTTPS, but doesn't send HSTS on its own. This header orders the browser to use only HTTPS for your domain for a given time. To add it, first put header Strict-Transport-Security "max-age=300" (five minutes) in the Caddyfile block. Once you're sure, switch to max-age=31536000 (one year): a misconfigured HSTS is hard to undo.
Caddy writes its logs to systemd's journal. sudo journalctl -u caddy -n 20 prints the last 20 lines of the caddy service (-u). The sudo is needed: without it, deploy can't see the services' journal. Add -f to follow them live.
A 502 Bad Gateway means Caddy can't reach PHP-FPM. Look in the journal for permission denied: that's the group from the previous section. Also look for a missing socket: that's a version number that doesn't match in the path.
Your turn: validate, reload, check
Your DNS points to the VPS, Caddy is installed, caddy is in the www-data group and the Caddyfile is written. What's left is to make it take effect and watch the certificate arrive.
After a deployment: reloading PHP-FPM
You change one line in a controller, refresh the page, and nothing moves: PHP-FPM is still serving the old code.
PHP-FPM doesn't reread your files on every visit. It keeps the code already translated into machine instructions (called "compiled") in memory, thanks to opcache. By default, it checks every two seconds whether a file has changed.
In production, this check is often turned off (opcache.validate_timestamps=0) to go faster. Nothing then tells PHP-FPM about new code. The safe reflex, after each update, is to reload it:
sudo systemctl reload php8.3-fpm
reload rereads the configuration and empties the memory. New requests see the new code. restart stops then relaunches the whole service. The reload is almost instant. A request running at that exact moment may fail: it's invisible for a small site. The process_control_timeout setting exists to avoid it, and we don't need it here. The next lesson's deployment script will use reload.
Nginx + certbot, honestly: nginx is another very common web server, and certbot is the tool that gets certificates for it. Together they give exactly the same result as Caddy. The difference: a longer configuration, and two tools to make coexist. We start with Caddy, and you can always switch.
🎯 Pratique
S'entraîner (clique pour ouvrir) :
💬 Ré-explique sans regarder
Que doivent avoir fait le DNS et le firewall pour que Caddy obtienne son certificat, et comment Caddy passe-t-il une requête à PHP-FPM ?
- L'enregistrement A pointe déjà vers l'IP du VPS.
- Les ports 80 et 443 sont ouverts : Let's Encrypt fait l'épreuve ACME par l'un ou l'autre.
- Le certificat dure 90 jours, et Caddy le renouvelle seul.
php_fastcgi passe la requête à PHP-FPM par la socket Unix /run/php/php8.3-fpm.sock. Pour y accéder, caddy doit être dans le groupe www-data. Et root pointe sur public/.🧠 Rappel libre
Sans remonter : vers quel dossier pointe root dans le Caddyfile, et pourquoi pas la racine du projet ?
/opt/app/public. À la racine du projet se trouvent .env.local, .git/ et composer.json. Caddy les servirait comme des fichiers statiques. .git/ et composer.json seraient téléchargeables, et .env.local ne tiendrait que grâce à ses droits de fichier.⚖️ Juge le conseil de l'IA
Ton site répond 502 et le journal de Caddy dit : dial unix /run/php/php8.3-fpm.sock: connect: permission denied. L'IA répond : « Lance sudo chmod 777 /run/php/php8.3-fpm.sock et ça repart. » Tu acceptes, ou tu rejettes ?
chmod 777 ouvre la socket à tous les comptes de la machine, pas seulement à Caddy. PHP-FPM recrée sa socket à chaque redémarrage, avec ses réglages d'origine. La « réparation » saute donc au prochain reboot. Tu chercheras le problème à 3h du matin. La vraie cause : l'utilisateur caddy n'est pas dans le groupe propriétaire de la socket. Lance sudo usermod -aG www-data caddy puis sudo systemctl restart caddy. C'est un seul accès ajouté, durable, au bon compte.Your site is on HTTPS, but updating it is still all by hand, never the same twice. Lesson 6 puts it all in a deployment script, with a 20-second rollback (a way back to the previous version).
Lesson 6: Deploying with a script →