16

I have two hostnames sharing the same domain name which I want to serve over HTTPs. I've got a wildcard-SSL certificate and created two vhost configs:

Host A

listen      127.0.0.1:443 ssl;
server_name     a.example.com;
root        /data/httpd/a.example.com;
ssl_certificate /etc/ssl/wildcard.cer;
ssl_certificate_key /etc/ssl/wildcard.key;

Host B

listen      127.0.0.1:443 ssl;
server_name     b.example.com;
root        /data/httpd/b.example.com;
ssl_certificate /etc/ssl/wildcard.cer;
ssl_certificate_key /etc/ssl/wildcard.key;

However, I get the same vhost served for either hostname.

vincent.io
  • 935
  • 3
  • 8
  • 23

2 Answers2

21

You need to split vhosts from ssl listening/configuration part:

Listening part:

server {
  listen              127.0.0.1:443 default_server ssl;
  server_name         _;
  ssl_certificate     /etc/ssl/wildcard.cer;
  ssl_certificate_key /etc/ssl/wildcard.key;
}

And now vhosts:

server {
  listen      127.0.0.1:443;
  server_name a.example.com;
  root        /data/httpd/a.example.com;
}

server {
  listen      127.0.0.1:443;
  server_name b.example.com;
  root        /data/httpd/b.example.com;
}
Teftin
  • 1,931
  • 17
  • 9
  • This wouldn't work. A vhost needs `ssl_certificate` and `ssl_certificate_key` that should be configured inside `server` or `http` location. In your example, you have declared it inside the first `server` location, but didn't declare it for the other two vhosts. – Pothi Kalimuthu Oct 27 '13 at 15:06
  • 2
    it's enough to configure `ssl_certificate`, `ssl_certificate_key` and `ssl` on default_server only. BTW, this config actually works. – Teftin Oct 27 '13 at 15:49
  • Unfortunately this doesn't work: nginx serves the same vhost content on both hosts. – vincent.io Oct 28 '13 at 12:11
  • 3
    Apparently you need to *restart* nginx instead of *reloading* it when doing these changes. Many thanks, your answer works like a charm :) – vincent.io Oct 28 '13 at 17:29
  • 1
    Thanks for this, I needed `ssl` on the `listen` directive for this to work with a 1.4.x nginx. My `listen` directives in the vhosts also had to be literally the same (logical equivalence was not sufficient). – Dave S. Aug 19 '14 at 17:24
13

It's actually explained in the manual: http://nginx.org/en/docs/http/configuring_https_servers.html#certificate_with_several_names

ssl_certificate /etc/ssl/wildcard.cer;
ssl_certificate_key /etc/ssl/wildcard.key;
server {
  listen      443 ssl;
  server_name a.example.com;
  root        /data/httpd/a.example.com;
}
server {
  listen      443 ssl;
  server_name b.example.com;
  root        /data/httpd/b.example.com;
}

Now, if you have many sites, I suggest storing all of them in a folder with just the server{} part as above in single files, and an include directive in the main file to load all of them:

ssl_certificate /etc/ssl/wildcard.cer;
ssl_certificate_key /etc/ssl/wildcard.key;
include /etc/nginx/conf.d/subfolder/*;
BxlSofty
  • 653
  • 5
  • 11