Nginx – Redirect from port 80 to 443 with nginx and multiple servers

nginxredirectssl

To begin, I'm a bit new with nginx and a bit lost… I sadly didn't found any solution to this, so here is my problem. If it's a duplicate of an already existing question I apologize and I would be very pleased to see the answer.

I'm building my very first nginx server and I have two domain names, one of these has plenty of subdomains, and I wish to put a SSL redirect on all of these. Problem is that it works only once with a IPv6 listen (here on the default config), and nginx dosen't start if I put that same config on the other subdomains (each subdomain has its own server config file with its own 80 → 443 server redirect).

server {
listen 443;
listen [::]:443;

## All the config and stuff

}

server {
listen      80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name www.mydomainna.me mydomainna.me;
rewrite     ^   https://$server_name$request_uri? permanent;
}

This is the default config file, and it works like a charm.

However and this is the thing that bugs me, is that on this exact same config (less the default_server) for every single subdomain and my second domain name I must remove IPv6 or nginx dosen't want to start.

server {
listen 443;
listen [::]:443;

## All the config and stuff

}

server {
listen      80;
server_name subdomain.mydomainna.me;
rewrite     ^   https://$server_name$request_uri? permanent;
}

So my question here is : how can I tell to listen on IPv6 for all of my other config files ?

I'm sorry if I didn't explained my question in a adequate manner and if anyone of you has a solution, thanks.

Best Answer

According to this page the line below tells Nginx to listen on port 80 for both IP4 and IP6.

listen [::]:80 default_server;

You have two directives telling Nginx to listen on port 443, which is why you're getting the duplicate listen message. Just remove the first line below and it should work.

listen 443;
listen [::]:443;

Note that I knew nothing about Nginx IP6 until I spent 2 minutes on Google. A very small amount of research uncovered this solution.