Nginx: reverse proxy and http to https redirect

301-redirecthttpsnginxreverse-proxy

I currently use a reverse proxy to map my.domain.com to a port 5000, but would like to also redirect http traffic to https. I don't want to add SSL cert info, as that's all handled by Cloudflare.

Here's my working reverse proxy:

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

    proxy_set_header X-Real-IP  $remote_addr;

    location / {
        proxy_pass http://localhost:3000;
    }
}

Here's my broken (ERR_TOO_MANY_REDIRECTS) attempt at adding a https redirect to the reverse proxy.

server {
    listen 80;
    server_name my.domain.com;
    return 302 https://my.domain.com$request_uri;
}

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

    proxy_set_header X-Real-IP  $remote_addr;

    location / {
        proxy_pass http://localhost:3000;
    }
}

Best Answer

How do you expect your webserver to know whether a connection came to Cloudflare over HTTPS or HTTP? There's basically two options:

  1. Cloudflare sets a header, indicating whether or not the request came to them over HTTPS; or
  2. Connections to Cloudflare over HTTPS are proxied to you over HTTPS also.

I thought Cloudflare supported option 1, but I can't find any docs on it now. However, they definitely support option 2, and you don't even need to buy your own TLS certificate to do it. I would strongly recommend doing that, and enabling port 443 on your nginx server to use TLS.