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.

1 Answer 1

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;
    ...
}
1
  • 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. May 28, 2017 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.