232

Is there a way to share configuration directives across two nginx server {} blocks? I'd like to avoid duplicating the rules, as my site's HTTPS and HTTP content are served with the exact same config.

Currently, it's like this:

server {
  listen 80;
  ...
}

server {
  listen 443;

  ssl on; # etc.
  ...
}

Can I do something along the lines of:

server {
  listen 80, 443;
  ...

  if(port == 443) {
    ssl on; #etc
  }
}
ceejayoz
  • 32,910
  • 7
  • 82
  • 106

5 Answers5

318

You can combine this into one server block like so:

server {
    listen 80;
    listen 443 default_server ssl;

    # other directives
}

Official How-To

Drifter104
  • 3,773
  • 2
  • 25
  • 39
Jauder Ho
  • 5,507
  • 2
  • 19
  • 17
95

To clarify the accepted answer, you need to omit

SSL on;

and you just need the following for nginx version after 0.8.21

listen 443 ssl;

Reference:

Nginx Docs - Configuring A single HTTP/HTTPS server

Sean Tan
  • 1,051
  • 7
  • 2
32

I don't know of a way like you suggest, but there's certainly an easy and maintainable way.

Move common server settings into a separate file, i.e. "serverFoo.conf" and then include it in separate server {} blocks like so:

server {
    listen 80;
    include serverFoo.conf;
}
server {
    listen 443 ssl;
    include serverFoo.conf;
}
Artur Bodera
  • 224
  • 2
  • 7
dwc
  • 1,528
  • 12
  • 10
12

Expanding on the already helpful answers, here is a more complete example:

server {

    # Listen on port 80 and 443
    # on both IPv4 and IPv6
    listen 80;
    listen [::]:80 ipv6only=on;
    listen 443 ssl;
    listen [::]:443 ipv6only=on ssl;

    # Set website folder
    root /path/to/your/website;

    # Enable SSL
    ssl_certificate your-cert.pem;
    ssl_certificate_key your-cert.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
    ssl_prefer_server_ciphers on;
}
Jonathan
  • 221
  • 2
  • 3
  • 2
    I know this is a pretty old answer, but as it's very complete I just wanted to point out for others who may use it that you should disable the SSLv3 protocol as its vulnerable to the POODLE vulnerability: https://disablessl3.com/ Instead use: ssl_protocols TLSv1 TLSv1.1 TLSv1.2; – user147787 Jan 06 '15 at 23:32
6

Just to add to Igor/Jauder's post, if you're listening to a specific IP you can use:

listen xxx.xxx.xxx.xxx;
listen xxx.xxx.xxx.xxx:443 default ssl;
Matt Bostock
  • 61
  • 1
  • 1