NGINX: HTTP to HTTPS redirect not working

amazon ec2httphttpsnginx

First time posting here. I've been searching on here for about two days to find a solution to my problem and nothing is working.

I know, there is a ton of posts about this same problem but none of the threads solutions I have came across, have worked so far. I am using NodeJS w/ Angular 5 on an Amazon EC2 instance.

Navigating to https://example.com works fine. The web page loads correctly. But, http://example.com gives me the "Welcome to nginx!" page.

Here is my nginx server config blocks:

server {
    listen 443 ssl default_server;
    server_name example.com

    server_tokens off;
    charset utf-8;
}

... SSL config stuff ...

    location / {
      proxy_pass http://localhost:8000/;

      proxy_http_version 1.1;

      proxy_set_header Host               $host;
      proxy_set_header X-Real-IP          $remote_addr;
      proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto  $scheme;
      proxy_set_header Proxy "";
    }
}
server {
      listen 80;
      server_name example.com

      return 301 https://$host$request_uri;
}
  • Tried changing default_server to the port 80 block
  • Tried using $server_name instead of $host on the redirect line
  • Tried having the port 80 block on top of the port 443 block
  • Checked for syntax errors in the config files (everything is fine)

Also checked for any conflicting files (none that I saw linked to nginx.conf).

curl -I http://example.com
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Wed, 18 Jul 2018 04:18:49 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 31 Jan 2017 15:01:11 GMT
Connection: keep-alive
ETag: "5890a6b7-264"
Accept-Ranges: bytes

As you can see, when I curl http://example.com (not actually example.com), it returns a status of 200 rather than 301. Also, the "Network" tab in Firefox's developer tools, shows a status of 304.

Best Answer

Please use $server instead of $host

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

Please refer below docs. might be helpful https://www.digitalocean.com/community/questions/best-way-to-configure-nginx-ssl-force-http-to-redirect-to-https-force-www-to-non-www-on-serverpilot-free-plan-by-using-nginx-configuration-file-only