Configurar soporte HTTPS con Let's Encrypt

:bookmark: Esta es una guía para habilitar HTTPS en una instalación existente de Discourse utilizando Let’s Encrypt. Asume una instalación previa sin HTTPS habilitado.

:person_raising_hand: Nivel de usuario requerido: Administrador del sistema

:exclamation: Esta guía es solo para instalaciones existentes donde HTTPS no está habilitado. Seguir la guía de configuración oficial habilita HTTPS automáticamente de forma predeterminada.

¿Te gustaría agregar HTTPS a tu Discourse absolutamente gratis, gracias a nuestros amigos de Let’s Encrypt?

:bell: ¿Está todo lo demás en tu sitio listo para HTTPS?

Antes de comenzar, ten en cuenta que para que HTTPS funcione correctamente, cada recurso individual de la página debe ser compatible con HTTPS. Considera tu CDN, tus inicios de sesión sociales, tus archivos de logotipo, cualquier JavaScript de terceros, imágenes, fuentes o CSS — ¡todos ellos deben estar disponibles a través de HTTPS!

Nota: ./discourse-setup habilitará Let’s Encrypt. Y desde marzo de 2017, puedes ejecutarlo nuevamente, presionar Intro varias veces e ingresar tu dirección de correo electrónico; el script incluirá las plantillas necesarias e insertará tu correo electrónico según sea necesario. A menos que seas un administrador de sistemas experto y sepas una razón para no hacerlo, deberías ejecutar discourse-setup en lugar de leer más. (Si instalaste Discourse hace mucho tiempo, es posible que aún tengas que editar app.yml manualmente.)

Nota: Si tu Discourse se accede a través de algún proxy inverso (por ejemplo, Cloudflare), esta configuración no funcionará.

Configurar HTTPS con Let’s Encrypt

1. Editar app.yml

Accede al archivo de configuración de tu Discourse:

cd /var/discourse
nano containers/app.yml
  • Agrega las siguientes plantillas:
    templates:
      - "templates/web.template.yml"
      - "templates/web.ssl.template.yml"
      - "templates/web.letsencrypt.ssl.template.yml"
    

:warning: ¿Es Discourse el único sitio web en tu servidor?

Si ya estás usando web.socketed.template.yml, porque alojas otros sitios web a través del puerto 80 en el mismo servidor, detente. Deberías usar un cliente de Let’s Encrypt en el sistema host; la validación fallará ya que el cliente utilizado no puede enlazar con los sockets necesarios.

2. Exponer puertos HTTPS

Asegúrate de que los siguientes puertos estén expuestos para el tráfico HTTPS:

expose:
  - "80:80"
  - "443:443"

3. Agregar correo electrónico para Let’s Encrypt

Inserta la dirección de correo electrónico para las notificaciones de Let’s Encrypt:

env:
  LETSENCRYPT_ACCOUNT_EMAIL: 'tu-correo@ejemplo.com'

4. Reconstruir la aplicación

Aplica los cambios reconstruyendo el contenedor:

./launcher rebuild app

5. Validar HTTPS

Accede a tu sitio a través de https://tudominio.com. Si tiene éxito, verás tu sitio asegurado con HTTPS.

Revisa tus recursos:

  • Asegúrate de que los activos (por ejemplo, imágenes, scripts) se carguen a través de HTTPS.
  • Reconfigura los inicios de sesión sociales y el CDN para HTTPS según sea necesario.
  • Aborda cualquier advertencia en la consola del navegador sobre activos inseguros.

Discourse habilita automáticamente force_https después de una reconstrucción con un certificado HTTPS válido.

¿Cómo funciona?

La plantilla utiliza GitHub - acmesh-official/acme.sh: A pure Unix shell script ACME client for SSL / TLS certificate automation · GitHub que es

El script de shell más simple para el cliente de certificados gratuitos de LetsEncrypt

Simple y poderoso, solo necesitas 3 minutos para aprenderlo.

Escrito puramente en bash, sin dependencias de python, acme-tiny ni el cliente oficial de LetsEncrypt. Solo un script para emitir y renovar tus certificados automáticamente.

Probablemente sea el script de shell más pequeño, fácil e inteligente para emitir y renovar automáticamente los certificados gratuitos de LetsEncrypt.

web.letsencrypt.ssl.template.yml agrega un script de inicio a tu contenedor que

  1. Inicia un nginx ligero para servir desafíos ACME en el puerto 80 antes de que el nginx principal esté activo.
  2. Emite tanto un certificado RSA (4096 bits) como un certificado ECDSA (ec-256) de Let’s Encrypt utilizando el modo webroot con /var/www/discourse/public como directorio.
  3. Instala los certificados en el directorio /shared/ssl/ que espera nginx. Al mismo tiempo, configura un trabajo cron para la renovación automática de certificados. Esto renovará automáticamente tus certificados. No sucede nada si los certificados no han expirado. Si un certificado expira, recibirás un correo electrónico al respecto de Let’s Encrypt en la dirección de correo electrónico que proporcionaste durante la configuración.
  4. Establece force_https en verdadero si se obtienen certificados válidos.

Solución de problemas

Revisar registros

Si HTTPS no funciona, revisa los registros de errores SSL o de Let’s Encrypt con:

./launcher logs app

Verificar archivos de certificación

Asegúrate de que los archivos de certificado y clave estén en su lugar con:

ls -l /var/discourse/shared/standalone/ssl

Deberías ver archivos como:

  • tudominio.com.cer (RSA)
  • tudominio.com.key (RSA)
  • tudominio.com_ecc.cer (ECDSA)
  • tudominio.com_ecc.key (ECDSA)

Renovar certificados manualmente

Si la renovación automática falla, puedes volver a emitir manualmente tus certificados:

./launcher enter app
sv stop nginx
/usr/sbin/nginx -c /etc/nginx/letsencrypt.conf
LE_WORKING_DIR=/shared/letsencrypt DEBUG=1 /shared/letsencrypt/acme.sh --issue -d ejemplo.com -k 4096 -w /var/www/discourse/public
LE_WORKING_DIR=/shared/letsencrypt /shared/letsencrypt/acme.sh --installcert -d ejemplo.com --fullchainpath /shared/ssl/ejemplo.com.cer --keypath /shared/ssl/ejemplo.com.key --reloadcmd "sv reload nginx"
LE_WORKING_DIR=/shared/letsencrypt DEBUG=1 /shared/letsencrypt/acme.sh --issue -d ejemplo.com --keylength ec-256 -w /var/www/discourse/public
LE_WORKING_DIR=/shared/letsencrypt /shared/letsencrypt/acme.sh --installcert --ecc -d ejemplo.com --fullchainpath /shared/ssl/ejemplo.com_ecc.cer --keypath /shared/ssl/ejemplo.com_ecc.key --reloadcmd "sv reload nginx"
/usr/sbin/nginx -c /etc/nginx/letsencrypt.conf -s stop

Reconstruir con certificados limpios

Elimina los archivos de certificados antiguos y reconstruye para comenzar de nuevo:

rm -rf /var/discourse/shared/standalone/ssl
rm -rf /var/discourse/shared/standalone/letsencrypt
./launcher rebuild app

Limitaciones

Los certificados de Let’s Encrypt solo validan el dominio y el cifrado. No confirman la propiedad o la identidad, lo cual puede ser marcado en algunos navegadores. Para más detalles, consulta la comunidad de Let’s Encrypt.

143 Me gusta
Setting up Let's Encrypt for multisite
How should I enable letsencrypt while discourse is beside other websites
Cant setting SLL (Let's Encrypt) for Discourse
Add to homescreen banner on Android
How to Set Up SSL in Discourse
Setting up SSL with my domain name and Discourse instance
Issue installing on subdomain
Completely automated SSL certificate generation
German 1&1-hosting user experience?
Problem with my SSL certificate
Replacement for whitelist-iframe
Site throws a blank screen after trying to enable LetsEncrypt
Missing file(discourse.conf) when launching after lets encrypt update?
Missing file(discourse.conf) when launching after lets encrypt update?
My discourse has either been hacked or catfished?
Discourse has stopped opening
Using a certificate when Discourse is installed behind a reverse proxy
Can discourse be installed in private mode
My Forum Is showing "Privacy Error" after upgrading SSL certificate
Using a certificate when Discourse is installed behind a reverse proxy
Why my forum not pop-up "Add to Home screen"(PWA) automatically?
Why my forum not pop-up "Add to Home screen"(PWA) automatically?
HTTPS : issue while trying to set up SSL certification
HTTPS : issue while trying to set up SSL certification
SSL received a record that exceeded the maximum permissible length
Discourse site loads via IP but via domain only header
Why is the Apple Touch Icon loaded via HTTP instead of HTTPS?
Defaultish app won't rebuild
Why is the Apple Touch Icon loaded via HTTP instead of HTTPS?
Why is the Apple Touch Icon loaded via HTTP instead of HTTPS?
Defaultish app won't rebuild
Unable to connect Discourse and WordPress
I have a very difficult problem installing ssl - please help
Not able to access site after letsencrypt cert expiry and rebuild due to IPV6
Cannot connect to IP address and no errors in log
Http logo urls after enabling LetsEncrypt
How to install SSL certificate in Discourse
White blank page on mobile app
Cloud installation not working
My forum goes offline after removing https
Trying to use Let's Encrypt + Cloudflare
New user invite links only give ERR_SSL_PROTOCOL_ERROR
[DigitalOcean] hostname having "www" in A records showing blank page
Error at LetsEncrypt validation
Migrate a phpBB3 forum to Discourse
Set Up Let's Encrypt with Second Domain for Existing Discourse Install
Not starting up after rebuild
Port 443 of computer does not appear to be accessible
Make auto-linked URLs use HTTPS
Unable to change domain name
LetsEncrypt certificate not renewing
How to deny request from unauthorized domain pointing to my IP address?
No login is possible after recovery a Discourse Backup on a new server
Letsencrypt issued on every build?
My Discourse is Down. Certificate Issue?
Setup Let’s Encrypt + non-www > www
No connection accepted on http / https after fresh installation on Ubuntu 22.04 LTS
SSL certificate expired and after that - Error 404 Not Found
SSL didn't renew automatically and I can't manually renew it
443 address already in use? Letencrypt
Set up Let’s Encrypt with multiple domains / redirects
Using Discourse with Cloudflare: Best Practices
./launcher rebuild app error bootstrap failed with exit code 125
Set up Let’s Encrypt with multiple domains / redirects
Uncaught ReferenceError: Discourse is not defined due to Cloudflare Rocket Loader
Let's Encrypt SSL Certificate Not Renewing
Uploads paths have 80 port but protocol is https
Bootstrap error during Discourse install: ENOENT - /etc/runit/1.d/letsencrypt
How to install Discourse in the AWS EC2 Instances(Ubuntu Server LTS)?
Question about the email configuration
Discourse-saml: There was an error authorizing your account
Problem in installing Let's Encrypt SSL for www and non-www
Email not sending out after installation. I need help please
Discourse not starting up: nginx: unable to open supervise/ok: file does not exist
Failed to bootstrap: Failure with receiving network data
Error when installing ssl Let's Encrypt
How to adjust dependencies for https?
Clicking links is stuck in click tracking, shows ERR_FAILED
Minimum needed to get LetsEncrypt working on a GCE instance
Can we install discourse in another container distro?
Problem with my SSL certificate
Cant setting SLL (Let's Encrypt) for Discourse
[PAID] setup ssl - Let's encrypt
Error after moving from HTTP to HTTPS
How to renew Let's Encrypt?
ServiceWorker script evaluation failed due to HTTP (not HTTPS)
Defaultish app won't rebuild
Too many redirects after enabling https