Search code examples
httpnginxhttpsreverse-proxyhttp-redirect

Nginx - Redirect HTTP to HTTPS in Reverse Proxy to Remote Site


I'm really looking for a kind of a hint in solving a problem with nginx reverse proxy. Right now I have a config silimar to this:

server {
  listen 443 ssl http2;
  server_name example.net;

  ssl_certificate /etc/nginx/certs/example.crt;
  ssl_certificate_key /etc/nginx/certs/example.key;

  location / {

     resolver 1.1.1.1 ipv6=off;
     proxy_ssl_server_name on;
     proxy_pass https://<example.com>:443;
  }
}

So basically this configuration makes this: you type https://example.net into your browser and you get the contents of https://example.com in response, but the initial domain stays the same (example.net).

As a finish move I want to make an HTTP to HTTPS redirect while accessing example.net. Let me explain: like you type only example.net into your browser and it automatically responses back to you with https://example.net contents, but the domain stays the same (example.net).

I tried the following approach:

server {
  listen 80;
  server_name example.net;

  return 301 https://example.com:443$request_uri;

}

I also tried proxy_pass directive and changed example.com to example.net in permanent redirect directive. None of it seems to work properly.

While investigating developers console in Chrome browser I get NS_BINDING_ABORTED which typically says that the initial request was modified before being finished.

So guys, let me know where I'm mistaken. Is it real to make it work? Thanks in advance!


Solution

  • As you want automatic redirect from HTTP to HTTPS. For that your Nginx config file should look like following.

        server {
                if ($host = example.net) {
                    return 301 https://$host$request_uri;
                }
            
              server_name example.net;
              listen 80;
            }
    
        server {
              listen 443 ssl http2;
              server_name example.net;
        
              ssl_certificate /etc/nginx/certs/example.crt;
              ssl_certificate_key /etc/nginx/certs/example.key;
        
            location / {
        
              resolver 1.1.1.1 ipv6=off;
              proxy_ssl_server_name on;
              proxy_pass https://<example.com>;
          }
        }