'Redirect to https with hunchentoot

I've set up a hunchentoot server with ssl. I'd like regular http requests to be redirected to https.

It seems like some combination of hunchentoot:define-easy-handler and hunchentoot:redirect is the way to go, but I can't figure it out.

Here's what I have so far:

(defvar *https-handler*
  (make-instance 'hunchentoot:easy-ssl-acceptor
                 :name 'ssl
                 :ssl-privatekey-file #P"/path/to/privkey.pem"
                 :ssl-certificate-file #P"/path/to/cert.pem"
                 :port 443))

(hunchentoot:start *https-handler*)


Solution 1:[1]

Well, I am using the hunchentoot:*dispatch-table* directly. The way to redirect it independent of the path I discovered was to hunchentoot:redirect unless (hunchentoot:ssl-p) inside the handler. Most of my defuned handlers are wrapped inside a macro for authenthentication. So, I merely had to modify that macro, and then M-x slime-who-macroexpands -> C-c C-k.

(unless (hunchentoot:ssl-p)
  (hunchentoot:redirect (hunchentoot:request-uri*)
                       :protocol :https))

Solution 2:[2]

If you need to indiscriminately redirect every HTTP request to HTTPS, using easy-acceptor is unnecessary. I'd suggest to define a specialized acceptor:

(defclass http-to-https-acceptor (hunchentoot:acceptor) ())
(defmethod hunchentoot:acceptor-dispatch-request ((acceptor http-to-https-acceptor) request)
  (hunchentoot:redirect (hunchentoot:request-uri request)
                        :protocol :https))

Then at some point:

(hunchentoot:start (make-instance 'http-to-https-acceptor :port 80))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 digikar
Solution 2 ffj