Get Let's Encrypt certs with HAProxy and Nginx

Get Let's Encrypt certs with HAProxy and Nginx

let's encrypt with haproxy & nginx

I have used Nginx virtual host to get Let’s Encrypt SSL certificates, it’s easy and straight forward. However, when HAProxy was added in front of Nginx, some issues arised. So let’s see how to deal with it.

The problems

Let’s Encrypt authorizes a certificate for a server by requesting a file via an HTTP(S) request. However, HAProxy is not a web server like that Nginx does. It won’t serve files by itself - it will only redirect a request to another server. And the “another server” will configured to Nginx here.

HAProxy setup

When we request a new certificate, Let’s Encrypt will request the authorization file (a URI like /.well-known/acme-challenge/random-hash-here). This request will happen over port 80. Within HAProxy, we need to set an acl if the incoming HTTP request contains the string /.well-known/acme-challenge, and route the request to Nginx (let’s say it’s listening on port 8888).

frontend http_frontend
	bind *:80
	mode http
	tcp-request inspect-delay 10s

	# Let's Encrypt certbot path
	acl certbot-acl path_beg /.well-known/acme-challenge/

	use_backend letsencrypt if certbot-acl

backend letsencrypt
	mode http
	server nginx localhost:8888 check

Reload HAProxy to make configurations take effect (sudo systemctl reload haproxy).

Nginx setup

Here is the relevant Nginx config:


server {
    listen 8888;
    listen [::]:8888;
    root /var/www/html;

    location ~ /.well-known/acme-challenge {
        allow all;

Notice that the default Nginx server should not listening on port 80 since HAProxy will use it.

New certificates

Run the following command to generate new certificates from Let’s Encrypt:

sudo certbot certonly -d demo.example.com \
    --non-interactive --agree-tos --email [email protected] \
    --webroot -w /var/www/html

It should put the new certificate in /etc/letsencrypt/live if everything worked.

Renew certificates

To renew the certs getting more easier:

sudo certbot renew -d demo.example.com \
    --webroot -w /var/www/html

Okay, this is how to put these three all together.


Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.4 billion 🇨🇳. This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.


Basics of load balancing with HAProxy



Basics of load balancing with HAProxy

HAProxy is free, open source software that provides a high availability load balancer and proxy server for TCP and HTTP-based applications. Its most common use is to improve the performance and reliability of a server environment by distributing the workload across multiple servers (e.g. web, application, database).