0

I have an /etc/nginx/nginx.conf with this basic structure:

http {
  server {
    listen 80;
    server_name example.com;
    root /var/html;
    location / {
      rewrite ...;
    }
  }
  server {
    listen 443;
    server_name example.com;
    root /var/html;
    location / {
      rewrite ...;
    }
  }
}

There are many rewrite directives, all identical between the http and https server blocks, so I tried to extract them into an external file:

http {
  server {
    listen 80;
    include /etc/nginx/redirects.conf;
  }
  server {
    listen 443;
    include /etc/nginx/redirects.conf;
  }
}

The redirects.conf file just contains:

server_name example.com;
root /var/html; 
location / {
  rewrite ...;
}

nginx -t -c /etc/nginx.conf tells me the syntax is fine, but the rewrite rules aren't taking effect. I know the file is being evaluated because if I introduce a syntax error, nginxs barfs. But the rewrites are ignored unless I keep them in the main nginx.conf file.

Workaround I will probably use: make use of the "map" module (sample answer showing how this is done here). Another thing I could use is Ansible to template out the config file, at least making the duplication machine-generated, but I'd still like to know why this is happening to better understand the limitations of the include directive.

Greg Hurrell
  • 103
  • 4

1 Answers1

1

If your server blocks are identical (except for the ssl settings), you can just combine them.

A single HTTP/HTTPS server

It is possible to configure a single server that handles both HTTP and HTTPS requests:

server {
    listen              80;
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ...
}
Esa Jokinen
  • 46,944
  • 3
  • 83
  • 129
  • Awesome. Have been serving SSL via nginx for years and didn't know this. Also, for reference, the `map` technique I mentioned above works fine. – Greg Hurrell May 28 '17 at 20:56