Nginx SSL on localhost

Sunil Antony asked:

I am trying to configure SSL on my localhost using Nginx. I created a self-signed certificate and my Nginx configuration is as below:

server {
  listen 443 ssl;
  server_name localhost;

  root /usr/share/nginx/html;
  index index.html index.htm;

  ssl on;
  ssl_certificate /etc/nginx/ssl/nginx.crt;
  ssl_certificate_key /etc/nginx/ssl/nginx.key;

  ssl_session_timeout 5m;

  ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
  ssl_prefer_server_ciphers on;

  location / {
        try_files $uri $uri/ =404;

But when I try accessing it gives me following error

$ curl -i https://localhost            
  curl: (7) Failed to connect to localhost port 443: Connection refused

What could be the possible cause for this error?

This is the output of command ‘netstat -tuplen’

tcp    0     0*      LISTEN     0    71662       - 

My answer:

You are missing a listen directive:

listen [::]:443 ssl;

This tells nginx to listen for IPv6 connections. Your existing listen directive listens only for IPv4 connections, and this is borne out in your netstat output.

The reason this is required (in addition to the existing listen directive) is that localhost resolves to an IPv6 address ::1 in addition to the historic IPv4 address But, IPv6 is the preferred protocol for making connections. Thus curl is attempting to connect to nginx via IPv6 and failing.

Of course, on the global Internet which you will (probably) eventually put your site on, you also will have to use IPv6, either now or in the near future. So you should prepare for this today.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.