Using nginx and certbot

If you do not have a reverse proxy already in place, you may run nginx as a reverse proxy, directly on the machine running Keycloak. You can also obtain an SSL/TLS certificats for free using certbot, an automated script to request Let’s Encrypt certificates.

6.1 Install the packages

> apt install certbot nginx-full python3-certbot-nginx

6.2 Request the certificate

Here, we assume your public DNS is keycloak.com, replace it with your actual DNS for the server.

> certbot --nginx -d keycloak.com

When prompted:

  • enter an email address (that will be communicated to Let’s Encrypt)
  • accept the terms
  • decide whether you want to share your email with the EFF
  • choose to redirect all HTTP traffic to HTTPS (this will modify the default nginx site appropriately)

Normally, the certbot service is already installed and should automatically renew your certificate (which is only valid for 3 months). You can check this with:

> systemctl status certbot.timer

⚠️⚠️ nginx does not auto-reload new certificates ⚠️⚠️

By default, nginx does not automatically reload its configuration when the certificate is renewed by certbot. This might also be the case for other HTTP servers. To make sure your server always uses the most up-to-date certificate, it is recommended to force it to reload its configuration on a regular basis. For nginx you may run the command

> systemctl reload nginx

You may also create a cron task to run this on a daily basis.

6.3 Configure nginx

Now, we need to create the nginx configuration file that will actually redirect HTTPS requests towards Keycloak. Create /etc/nginx/sites-available/keycloak.conf containing:

server { server_name keycloak.com; # To only redirect a specific set of paths, you may replace the line below with something of the form # location ~ ^(/auth/resources/|/auth/js/|/auth/realms/olvid/) { location /auth { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_pass http://127.0.0.1:8080; } location /olvid { return 302 /auth/olvid/#; } location = / { return 302 /auth; } client_max_body_size 10M; listen [::]:443 ssl ipv6only=on; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/keycloak.public.dns/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/keycloak.public.dns/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } server { server_name keycloak.public.dns; listen [::]:80; listen 80; return 301 https://$host$request_uri; }

Now, to activate this configuration and deactivate the default configuration:

> cd /etc/nginx/sites-enabled
> rm default
> ln -s ../sites-available/keycloak.conf .
> systemctl restart nginx

That’s it, you should now be able to connect to your keycloak server through its public DNS.