nginx split large configuration file

Solution 1:

You are probably looking for Nginx's include function:

You can use it like this:

server {
  listen 80;
  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.

Solution 2:

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:

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"
    mv "$i" $new.conf

(I enhanced this from this source: )

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 here
    listen 80;