8

I'm trying to force SSL on my site. I want to have a ring style middle-ware to redirect the site to the same URL with https if it is only http

I wrote the following code but it doesn't really do anything besides check the request scheme and print the URL it should be redirecting to.

(defn https-url [request-url]
  (str (str (str (str "https://" (:server-name request-url) ":") (:server-port request-url))) (:uri request-url)))

(defn require-https
  [handler]
  (fn [request]
    (let [page-request (handler request)]
      (if (= (:scheme page-request) :http)
        (println (https-url page-request))))))

(server/add-middleware require-https)

How would I implement this into a real app?

I'm using clojure 1.2 with Noir.

Side note: How do I combine multiple strings into one string with out using multiple nested str's?

animuson
  • 53,861
  • 28
  • 137
  • 147
kush
  • 16,408
  • 17
  • 48
  • 65

1 Answers1

7

You can use ring.util.response/redirect:

(fn handler [request]
  (if need-to-redirect?
    ;; NB. target-url should be a string
    (ring.util.response/redirect target-url)
    ...))

As for the side note, str is variadic:

(str "foo" 'bar "baz")
; => "foobarbaz"
Michał Marczyk
  • 83,634
  • 13
  • 201
  • 212
  • Hmm, its triggering that redirect function. But its not redirecting for some reason. Where should I place this? I currently have it in server.clj before -main definition – kush Feb 15 '12 at 23:48
  • You need to make the return value of `ring.util.response/redirect` the return value of your handler, possibly to be modified by outer middleware (which should leave the HTTP status and the "Location" header alone for the direct to succeed, of course). Example: https://refheap.com/paste/758 – Michał Marczyk Feb 16 '12 at 00:00
  • With noir the server handler is at a higher level of abstraction than in your example. So its not clear to me where to put it, heres my server.clj https://gist.github.com/1840261 I may be in over my head with this one :) – kush Feb 16 '12 at 00:11
  • 1
    Your handler always returns `request`; here's a fixed version with a moved paren and the wrapped `handler` applied to `request` in the no-redirect branch which I think should work: https://refheap.com/paste/760 – Michał Marczyk Feb 16 '12 at 00:27