51

My nginx default configuration file is becoming huge. I'd like to split it to smaller config files, each including only one, maximum 4 locations to each file, so that I can enable/disable them quickly.

Actual file looks like this:

server {
    listen 80 default_server;
    root /var/www/

    location /1 {
        config info...;
    }

    location /2 {
        config info....;
    }        
    location /abc {
        proxy_pass...;
    }

    location /xyz {
        fastcgi_pass....;
    }
    location /5678ab {
        config info...;
    }

    location /admin {
        config info....;
    }

now, if I want to split that up to have only a few locations in each file (locations belonging together), what would be a proper way to do it without causing chaos (like declaring root in each file, hence having weird path's that nginx tries to find files) ?

oliverjkb
  • 644

2 Answers2

63

You are probably looking for Nginx's include function: http://nginx.org/en/docs/ngx_core_module.html#include

You can use it like this:

server {
  listen 80;
  server_name example.com;
  […]
  include conf/location.conf;
}

include also accepts wildcards so you could also write

include include/*.conf;

to include every *.conf file in the directory include.

mat
  • 568
  • 1
  • 7
  • 21
FLXN
  • 778
8

You can create site folders with

mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled

# And then split your large your_config.conf file into smaller files into sites-available/ with:

YOURCONF="/etc/nginx/conf.d/your_config.conf"
cd /etc/nginx
mkdir -p sites-available sites-enabled
cd  sites-available/
csplit "$YOURCONF" '/^\s*server\s*{*$/' {*}
for i in xx*; do
  new=$(grep -oPm1 '(?<=server_name).+(?=;)' $i|sed -e 's/\(\w\) /\1_/g'|xargs);
  if [[ -e $new.conf ]] ; then
    echo "" >>$new.conf
    cat "$i">>$new.conf
    rm "$i"
  else
    mv "$i" $new.conf
  fi
done

(I enhanced this from this source: https://stackoverflow.com/a/9635153/1069083 )

Be sure to add this at the end inside the http block of your/etc/nginx/conf.d/*.conf;:

include /etc/nginx/sites-enabled/*.conf; 

Note: comments outside the server blocks are cut into the bottom of each file, so there should be no comments BEFORE a server block. Move comments in the first line INSIDE the block instead, example:

 # don't put comments here
 server {
    # put your comments about domain xyz.org here
    listen 80;
    server_name xyz.org;
    ...
rubo77
  • 2,537