1

I want to redirect from http to https in an NGINX server block.

Following an answer in a related post I tried adding another server block in the following NGINX config file, but got a 'conflicting server name' warning, as (presumably) the value of server_name doesn't include the protocol prefix:

server {
    listen 80;
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    server_name sub.domain.co.uk;
    return 302 https://sub.domain.co.uk$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    server_name sub.domain.co.uk;
    location / {
        root /home/saves/webapps/html/;
        index index.html;
    }
    location /api/ {
        [...]
   }
}
Dave Everitt
  • 201
  • 1
  • 4
  • 11

2 Answers2

3

The problem is that you have configured two server blocks listening for SSL on the same port with the same server name and there's no way for nginx to decide which one to choose in these conditions. Change it to :

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    return 302 https://sub.domain.co.uk$request_uri;
}

server {
    listen 443;
    server_name sub.domain.co.uk;

    location / {
        root /home/saves/webapps/html/;
        index index.html;
    }
    location /api/ {
        [...]
   }
}
Xavier Lucas
  • 13,095
  • 2
  • 44
  • 50
0

I thought about this, did a little research, and solved it with a much simpler server block before the main one, from this answer:

server {
    listen 80;                            
    location / {
        return 301 https://sub.domain.co.uk;
    }
}

But finally amended it after the comments to this:

server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    server_name sub.domain.co.uk;
    location / {
        return 301 https://sub.domain.co.uk;
        root /home/saves/webapps/html/;
        index index.html;
    }
    [...]
}

So thanks to you both for your swift and useful replies.

Dave Everitt
  • 201
  • 1
  • 4
  • 11