Let’s Encrypt + non-www > www


#1

I finally made it work, and thought to put everything together in case someone needs it.
This info is assembled from different topics on this forum. Thanks to @brahn and @techAPJ.
This assumes you’ve completed the initial Let’s Encrypt setup:

After you’ve done it, the following needs to be added to the app.yml in hooks section. It will do two things:

  1. setup SSL for both yourdomain.com and www.yourdomain.com. Just replace “yourdomain.com” with your domain name.
  2. redirect yourdomain.com to www.yourdomain.com

If anybody knows how to improve it, please let me know.

hooks:
  after_code:
    - exec:
        cd: $home/plugins
        cmd:
          - git clone https://github.com/discourse/docker_manager.git


  after_web_config:
    - replace:
        filename: /etc/nginx/nginx.conf
        from: /sendfile.+on;/
        to: |
          server_names_hash_bucket_size 64;
          sendfile on;
    - file:
        path: /etc/nginx/conf.d/discourse_redirect_1.conf
        contents: |
          server {
            listen 443;
            server_name yourdomain.com;
            return 301 $scheme://www.yourdomain.com$request_uri;
          }
  after_ssl:
    - replace:
        filename: "/etc/runit/1.d/letsencrypt"
        from: /-k 4096 -w \/var\/www\/discourse\/public/
        to: |
          -d www.yourdomain.com -d yourdomain.com -k 4096 -w /var/www/discourse/public

    - replace:
        filename: "/etc/runit/1.d/letsencrypt"
        from: /-k 4096 --force -w \/var\/www\/discourse\/public/
        to: |
          -d www.yourdomain.com -d yourdomain.com -k 4096 --force -w /var/www/discourse/public

    - replace:
        filename: "/etc/nginx/conf.d/discourse.conf"
        from: /return 301 https.+/
        to: |
          return 301 https://$host$request_uri;

    - replace:
        filename: "/etc/nginx/conf.d/discourse.conf"
        from: /gzip on;[^\}]+\}/m
        to: |
          gzip on;
          add_header Strict-Transport-Security 'max-age=31536000'; # remember the certificate for a year and automatically connect to HTTPS for th$

as always, remember that spacing and indentation is extremely important in the app.yml file. After you’ve done editing, you have to rebuild the container with:

cd /var/discourse
git pull
./launcher rebuild app

#2

I wonder if this part is needed, since we already have the “force https” option in Admin settings.
@brahn, this is your part of the code, can you explain why is this necessary?

- replace:
    filename: "/etc/nginx/conf.d/discourse.conf"
    from: /return 301 https.+/
    to: |
      return 301 https://$host$request_uri;

(Brahn) #3

I’m not really sure, does that setting redirect or just block non-https requests?