Sinatra + Reverse Proxy(Lighttpd) + SSL

Mon 28 Aug 2017
Reading time: (1 min)

So you made your first Sinatra app and you got it live on your server. You followed the simple steps here to get a sweet reverse proxy going with Lighttpd and Thin and everything is right in the universe. Then you hear some unsettling news...Google is slowly ramping its hunt for non-HTTPS pages. Time to get cracking.

Let's pretend this is our awesome app:

require 'sinatra'

get '/' do
  .. show something ..
end

Let's get the Sinatra side ready to OBEY Google.

Install Rack::SSL via your terminal:

gem install rack-ssl

And now let's use it to force HTTPS:

require 'sinatra'
require 'rack/ssl' #
use Rack::SSL      #

get '/' do
  .. show something ..
end

Pretty simple huh? Now we need to make sure we have a valid certificate to actually communicate securely. Thankfully in this day and age it's simple and free. The generous folks at Let's Encrypt want to see every site beefed up. Go to https://certbot.eff.org and select the software and server you are using. In our case software is none of the above and server is ...well honestly you should know, cause I have no idea what you are using.

The following section has been updated for 2020 at the following link: Updating Let's Encrypt for Lighttpd

Follow the instructions in the INSTALL section. Make sure to replace /path/to/my/app and mydomain.com with real values then run this via your terminal:

sudo certbot certonly --webroot -w /path/to/my/app -d mydomain.com -d www.mydomain.com

Now we have our own certificates! Lighttpd expects certs in a single file so let's do that:

cd /etc/letsencrypt/live/mydomain
cat privkey.pem cert.pem > ssl.pem

Lastly we edit our Lighttpd config, again replacing mydomain:

  $SERVER["socket"] == ":443" {
    ssl.engine = "enable"
    ssl.pemfile = "/etc/letsencrypt/live/mydomain/ssl.pem"
    ssl.ca-file =  "/etc/letsencrypt/live/mydomain/cert.pem"
    ssl.cipher-list = "ECDHE-RSA-AES256-SHA384:AES256-SHA256:HIGH:!MD5:!aNULL:!EDH:!AESGCM"
    ssl.honor-cipher-order = "enable"
    ssl.use-sslv2 = "disable"
    ssl.use-sslv3 = "disable"
  }

Reload Lighttpd:

/etc/init.d/lighttpd reload

and we should now be getting HTTPS everywhere!

Rejoice that we evaded Google's evil gaze for one more day. Next steps should be making sure your cert is always up to date by running this before every 90 days:

certbot renew 

Good luck out there.


Questions? Free free to contact me anytime :)

Get Notified of Future Posts