Where to define SSL config for multiple nginx server blocks

by lonix   Last Updated October 10, 2019 20:00 PM

I want to redirect http to https, and naked to www.

So my config:

# http naked -> https www
# http www -> https www
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://www.example.com$request-uri;

# https naked -> https www
server {
  listen 443 ssl http2;
  server_name example.com;
  #ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem     # <--- ??
  #ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem   # <--- ??
  return 301 https://www.$host$request-uri;

# https www
server {
  listen 443 ssl http2;
  server_name www.example.com;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem

Do I need to repeat the SSL stuff shown as ?? in the middle block?

Tags : nginx

Answers 1

Every ssl virtualhost must define key/cert. So in your case if you wrote "listen ... ssl", you have to write ssl_certificate lines. It is not important, if that key/cert pair will be used for anything else.

You can have aliases. I.e. if your key/cert pair in /etc/letsencrypt/live/example.com is valid for both example.com and www.example.com (i.e. that is SAN certificate), and you want to serve same content from www.example.com and example.com without redirect, you can have only one ssl vhost in nginx: server_name example.com www.example.com;

You can do redirect even in this case, but I think it is easier to understand and maintain a config if those are distinct vhosts.

Nikita Kipriyanov
Nikita Kipriyanov
October 10, 2019 19:33 PM

Related Questions

Updated September 16, 2019 18:00 PM

Updated August 03, 2019 14:00 PM

Updated March 27, 2015 07:00 AM

Updated March 26, 2015 14:00 PM