Redirect http://example.com:12345 to https://example.com:12345 in nginx

I know this must have been answered already, but I have been searching for quite a while, and cannot find the answer. Just not looking in the right place I guess, maybe someone can help me out.

Basically I am running phpmyadmin through SSL on a non-standard port, in this example 12345.

Now I have https://example.com:12345 set up ok, it works and everything. Now I want to add the ability to just type http://example.com:12345 and be redirected to the https://.

I asumed the following would work, but it does not.

server {
  listen        12345;
  server_name   php.myadmin.com;

  if ( $scheme = http ) {
    rewrite ^ https://php.myadmin.com:12345$request_uri? redirect;
  }
  root         /var/www/php;

  ssl           on;

  [....]
}

This gives me a 400 bad request.

Now before posting an answer make sure to have a good look at the redirect form. Check the pitfall in the link bellow.

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites

Further, it would be nice if this can even be done without an if-statement:

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#using-if


I do exactly this. gWaldo is correct, but you don't want to serve content over HTTP, just a redirect. The trick is to catch the http-on-an-https-port error and use that to bounce the client to the correct place.

server {
    listen   12345;
    server_name  my.domain.com;

    ssl on;
    ssl_certificate /etc/ssl/certs/your.pem;
    ssl_certificate_key /etc/ssl/private/your.key;

    # If they come here using HTTP, bounce them to the correct scheme
    error_page 497 https://$server_name:$server_port$request_uri;
    # Or if you're on the default port 443, then this should work too
    # error_page 497 https://$server_name$request_uri;

    location / {
        # Your config here...
    }
}

Unfortunately, you can't handle http and https requests using a single port with nginx.

What you can do is have a proxy pre-handle requests, however. This is how we handle the scheme-processing:

set $real_scheme http;
if ($http_x_forwarded_proto) { set $real_scheme $http_x_forwarded_proto; }

set $target_scheme https;

if ($real_scheme != $target_scheme) {
  rewrite ^ $target_scheme://$host$request_uri redirect;
}