Redirecting HTTP Requests on an HTTPS Listener in Nginx (Status Code 497)

Nginx has a bunch of custom https status codes that it uses internally to signal issues. One such status code is 497: the client made an http request on an https listener.

These custom status codes can be used in combination with an error_page directive which can be used to redirect.

server {
  listen 9090 ssl;
  # ssl config here ...

  error_page 497 =301 https://$host:$server_port$request_uri;

This will send a 301 permanent redirect to the https version of the page.

Use Cases

My particular use case is that I was using nginx to handle the TLS side of things in a local development environment. I was using a non standard port that was previously serving http traffic only. To make the switch to https seemless for the rest of the team, I wanted a redirect. A bit of googling turned up this obscure nginx feature.