Return json response when making a request with plain HTTP

Question

Currently, I’m serving an API in the subdomain api.example.com. I have turned on full HTTPS strict. The problem is that if a user tries to make a request to http://api.example.com, Cloudflare returns a 301 redirect status code with an empty body.

I would like to return a JSON response instead. Something like:

{
  "error": {
    "message" : "This API is only accessible over HTTPS.",
    "type": "invalid_request_error"
  }
}

To make my API more explicit. How can I do this? Can I achieve this with workers?

I believe the HTTPS redirect works long before Workers and everything else. In your case it probably is best to turn off “Always use HTTPS” and handle that redirect on your server side.

1 Like