Plack::Middleware::RedirectSSL

I just shipped 1.300 of this module to the CPAN and it occurs to me that I’ve never talked about it here. I suppose I figured that what it does is so simple that there’s not much to say about it. But it‘s useful if you need what it does, and I wrote it because nobody else had.

  1. Do you have a web site being served over HTTPS?
  2. Do you want to redirect visitors coming in over HTTP to HTTPS?
    (I.e. send visitors of
     http://example.org/some/where to
    https://example.org/some/where instead.)

If you answered yes once, you almost certainly answered yes twice. Right? It’s such a common thing to need.

But when I went looking for a way to make my PSGI application do that, I found nothing on CPAN.

Being that what I have is mainly a Catalyst application, I did find things like Catalyst::Plugin::RequireSSL, which was more complicated than I wanted, and Catalyst::ActionRole::RequireSSL, which does something else entirely. And of course, a Catalyst extension won’t help with the non-Catalyst parts my application has grown.

Somehow, nobody had written (something like) Plack::Middleware::RedirectSSL, so I had to. I did, and it does just what I described. (Or the opposite, i.e. redirecting visitors from HTTPS to HTTP, should you ever need that. I have, occasionally.)

An important part of the middleware is that it supports HTTP Strict Transport Security (HSTS, specified in RFC 6797), and that this is enabled by default. This is a header that tells browsers to always ask for links on the site using https:// even if the URL said http:// – in other words, once the browser has been to the site, it will automatically do the same thing the middleware would tell it to do using a redirect. Because no unencrypted HTTP requests are required to switch over to HTTPS, visitors are thus protected from attempts to hijack their initial request to the site (such as when they visit it by typing just the domain name into the address bar).

Note that while you should enable HSTS, you should not take it lightly – once you start telling browsers to always connect to your site using encryption, they will refuse to connect without valid encryption. That means you must stay on top of your SSL certificate at all times. If it expires or is revoked, users will be left unable to connect to your site.

The changes in version 1.300 of the module all relate to HSTS support. Previously only the max-age directive was supported – now you can also set the includeSubDomains and preload directives, and your policy will be validated. This new comprehensive HSTS support is also exposed as a render_sts_policy function which can be used independently from the middleware itself.

Share and enjoy.

Leave a comment

About Aristotle

user-pic Waxing philosophical