How to format and beautify Nginx configuration

Format and beautify Nginx configuration using dedicated utilities like nginx-config-formatter, nginxbeautifier and crossplane.

nginx configuration file

Sample configuration file that will be used in the following examples.

server {
        #listen 80 default_server;
        listen 443 ssl;

        ssl_certificate ssl/nginx.crt;
        ssl_certificate_key ssl/nginx.key;

        server_name _;

        root /var/www/html;
        index  index.html index.php;

        gzip on;
        gzip_disable "msie6";

        gzip_comp_level 6;
        # gzip_comp_level 9;
        gzip_min_length  1100;
        gzip_buffers 16 8k;                                                                                                                                                                                                                                                                 gzip_proxied any;
        # gzip_http_version 1.1;
        gzip_types       text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;

        client_max_body_size 300M;

        rewrite ^/oauth/authorize$ /server/php/authorize.php last;
        rewrite ^/oauth_callback/([a-zA-Z0-9_\.]*)/([a-zA-Z0-9_\.]*)$ /server/php/oauth_callback.php?plugin=$1&code=$2 last;
        rewrite ^/download/([0-9]*)/([a-zA-Z0-9_\.]*)$ /server/php/download.php?id=$1&hash=$2 last;
        rewrite ^/ical/([0-9]*)/([0-9]*)/([a-z0-9]*).ics$ /server/php/ical.php?board_id=$1&user_id=$2&hash=$3 last;
        rewrite ^/api/(.*)$ /server/php/R/r.php?_url=$1&$args last;
        rewrite ^/api_explorer/api-docs/$ /client/api_explorer/api-docs/index.php last;

        location / {
                root /var/www/html/client;
        }

        location ~ \.php$ {
                try_files $uri =404;
                include fastcgi_params;
                fastcgi_pass    unix:/run/php/php7.3-fpm.sock;
                fastcgi_index   index.php;
                fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param   PHP_VALUE "upload_max_filesize=80M \n post_max_size=120M \n max_execution_time=200 \n max_input_time=200 \n memory_limit=256M";
        }

        location ~* \.(css|js|less|html|ttf|woff|jpg|jpeg|gif|png|bmp|ico) {
                root /var/www/html/client;
                if (-f $request_filename) {
                        break;
                }
                rewrite ^/img/([a-zA-Z_]*)/([a-zA-Z_]*)/([a-zA-Z0-9_\.]*)$ /server/php/image.php?size=$1&model=$2&filename=$3 last;
                add_header        Cache-Control public;
                add_header        Cache-Control must-revalidate;
                expires           7d;
        }
}

nginx config file formatter

GitHub repository: https://github.com/1connect/nginx-config-formatter/

Clone git repository and copy Python script to install nginx config file formatter.

$ git clone https://github.com/1connect/nginx-config-formatter.git
$ sudo cp nginx-config-formatter/nginxfmt.py /usr/local/bin/

Help information.

$ nginxfmt.py -h
usage: nginxfmt.py [-h] [-v] [-b] config_files [config_files ...]

This Python script formats nginx configuration files in consistent way.
Originally published under https://github.com/1connect/nginx-config-formatter

positional arguments:
  config_files          configuration files to format

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         show formatted file names
  -b, --backup-original
                        backup original config file

Format nginx configuration file.

$ nginxfmt.py -v restyaboard
Formatted file 'restyaboard' (detected encoding utf-8).

Inspect nginx configuration file.

$ cat restyaboard
server {
    #listen 80 default_server;
    listen 443 ssl;

    ssl_certificate ssl/nginx.crt;
    ssl_certificate_key ssl/nginx.key;

    server_name _;

    root /var/www/html;
    index index.html index.php;

    gzip on;
    gzip_disable "msie6";

    gzip_comp_level 6;
    # gzip_comp_level 9;
    gzip_min_length 1100;
    gzip_buffers 16 8k;
    gzip_proxied any;
    # gzip_http_version 1.1;
    gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application
/xml+rss;

    client_max_body_size 300M;

    rewrite ^/oauth/authorize$ /server/php/authorize.php last;
    rewrite ^/oauth_callback/([a-zA-Z0-9_\.]*)/([a-zA-Z0-9_\.]*)$ /server/php/oauth_callback.php?plugin=$1&code=$2 last;
    rewrite ^/download/([0-9]*)/([a-zA-Z0-9_\.]*)$ /server/php/download.php?id=$1&hash=$2 last;
    rewrite ^/ical/([0-9]*)/([0-9]*)/([a-z0-9]*).ics$ /server/php/ical.php?board_id=$1&user_id=$2&hash=$3 last;
    rewrite ^/api/(.*)$ /server/php/R/r.php?_url=$1&$args last;
    rewrite ^/api_explorer/api-docs/$ /client/api_explorer/api-docs/index.php last;

    location / {
        root /var/www/html/client;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "upload_max_filesize=80M \n post_max_size=120M \n max_execution_time=200 \n max_input_time=200 \n memory_limit=256M";
    }

    location ~* \.(css|js|less|html|ttf|woff|jpg|jpeg|gif|png|bmp|ico) {
        root /var/www/html/client;
        if (-f $request_filename) {
            break;
        }
        rewrite ^/img/([a-zA-Z_]*)/([a-zA-Z_]*)/([a-zA-Z0-9_\.]*)$ /server/php/image.php?size=$1&model=$2&filename=$3 last;
        add_header Cache-Control public;
        add_header Cache-Control must-revalidate;
        expires 7d;
    }
}

nginx config file formatter and beautifier

GitHub repository: https://github.com/vasilevich/nginxbeautifier

Install nodejs at first.

$ sudo apt install curl gnupg2
$ curl -sSL https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
$ cat << EOF | sudo tee /etc/apt/sources.list.d/nodesource.list
deb https://deb.nodesource.com/node_12.x buster main
deb-src https://deb.nodesource.com/node_12.x buster main
EOF
$ sudo apt-get update
$ sudo apt-get install nodejs

Iinstall nginx config file formatter and beautifier.

$ sudo npm install -g nginxbeautifier

Help information.

$ nginxbeautifier --help
Usage: nginxbeautifier [OPTION]... [FILE]...
Description: Formats nginx conf files into a more readable format by re-indenting the lines.

Mandatory arguments to long options are mandatory for short options too, Arguments are case insensitive.
-h, --help,  Show this help text.
-s, --space,  Amount of spaces to indent with, Can not be used if tabs are specified.
-t, --tabs,  Amount of tabs to indent with, Can not be used if spaces are specified.
-bl, --blank-lines,  if set to true, an empty line will be inserted after opening brackets
-dj, --dontjoin, --dont-join,  if set to true, commands such as 'server' and '{' will be on a seperate line, false by default ('server {' )
-a, --align,  if set to true, all applicable attribute values will be vertically aligned with each other
-r, --recursive,  scan the whole current folder, and all sub folders recursively.
-i, --input,  The file to input, is optional if you provide a path after all the arguments.
-o, --output,  The file to output to, is optional if you provide a path after all the arguments.
-e, -ext, --extension,  The extension of the config file to look for(.conf by default).

Usage examples:
(1)>nginxbeautifier -s 4 -r sites-enabled/
(2)>nginxbeautifier -s 4 -r /etc/nginx/sites-enabled/
(3)>nginxbeautifier -s 4 -i /etc/nginx/sites-enabled/site.conf -o /etc/nginx/sites-enabled/newSite.conf
(4)>nginxbeautifier -s 4 -i /etc/nginx/sites-enabled/site.conf
(5)>nginxbeautifier -s 4 -i /etc/nginx/sites-enabled/*
(6)>nginxbeautifier -t 4 -i /etc/nginx/sites-enabled/*
(7)>nginxbeautifier -t 4 /etc/nginx/sites-enabled/*
(8)>nginxbeautifier -t 4 -i /etc/nginx/sites-enabled/* -o /etc/nginx/new-sites-enabled/*

Format nginx configuration file.

$ nginxbeautifier restyaboard
Working on file: restyaboard
Success.

Inspect nginx configuration file.

$ cat restyaboard
server {
        #listen 80 default_server;
        listen 443 ssl;

        ssl_certificate ssl/nginx.crt;
        ssl_certificate_key ssl/nginx.key;

        server_name _;

        root /var/www/html;
        index index.html index.php;

        gzip on;
        gzip_disable "msie6";

        gzip_comp_level 6;
        # gzip_comp_level 9;
        gzip_min_length 1100;
        gzip_buffers 16 8k;
        gzip_proxied any;
        # gzip_http_version 1.1;
        gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;

        client_max_body_size 300M;

        rewrite ^/oauth/authorize$ /server/php/authorize.php last;
        rewrite ^/oauth_callback/([a-zA-Z0-9_\.]*)/([a-zA-Z0-9_\.]*)$ /server/php/oauth_callback.php?plugin=$1&code=$2 last;
        rewrite ^/download/([0-9]*)/([a-zA-Z0-9_\.]*)$ /server/php/download.php?id=$1&hash=$2 last;
        rewrite ^/ical/([0-9]*)/([0-9]*)/([a-z0-9]*).ics$ /server/php/ical.php?board_id=$1&user_id=$2&hash=$3 last;
        rewrite ^/api/(.*)$ /server/php/R/r.php?_url=$1&$args last;
        rewrite ^/api_explorer/api-docs/$ /client/api_explorer/api-docs/index.php last;

        location / {
                root /var/www/html/client;
        }

        location ~ \.php$ {
                try_files $uri =404;
                include fastcgi_params;
                fastcgi_pass unix:/run/php/php7.3-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PHP_VALUE "upload_max_filesize=80M \n post_max_size=120M \n max_execution_time=200 \n max_input_time=200 \n memory_limit=256M";
        }

        location ~* \.(css|js|less|html|ttf|woff|jpg|jpeg|gif|png|bmp|ico) {
                root /var/www/html/client;
                if (-f $request_filename) {
                        break;
                }
                rewrite ^/img/([a-zA-Z_]*)/([a-zA-Z_]*)/([a-zA-Z0-9_\.]*)$ /server/php/image.php?size=$1&model=$2&filename=$3 last;
                add_header Cache-Control public;
                add_header Cache-Control must-revalidate;
                expires 7d;
        }
}

reliable and fast NGINX configuration file parser and builder

GitHub repository: https://github.com/nginxinc/crossplane

Install reliable and fast NGINX configuration file parser and builder.

$ sudo pip3 install crossplane
Collecting crossplane
  Downloading https://files.pythonhosted.org/packages/5b/f0/ef346efc7684e8a5e33565721e8aac345a272c1668ddeea9ea2780bf40d9/crossplane-0.5.4-py2.py3-none-any.whl
Installing collected packages: crossplane
Successfully installed crossplane-0.5.4

Help information

$ crossplane  --help
usage: crossplane  [options]

various operations for nginx config files

optional arguments:
  -h, --help            show this help message and exit
  -V, --version         show program's version number and exit

commands:
  parse                 parses a json payload for an nginx config
  build                 builds an nginx config from a json payload
  lex                   lexes tokens from an nginx config file
  minify                removes all whitespace from an nginx config
  format                formats an nginx config file
  help                  show help for commands

Format nginx configuration file.

$ crossplane format restyaboard
server {
    #listen 80 default_server;
    listen 443 ssl;
    ssl_certificate ssl/nginx.crt;
    ssl_certificate_key ssl/nginx.key;
    server_name _;
    root /var/www/html;
    index index.html index.php;
    gzip on;
    gzip_disable msie6;
    gzip_comp_level 6;
    # gzip_comp_level 9;
    gzip_min_length 1100;
    gzip_buffers 16 8k;
    gzip_proxied any;
    # gzip_http_version 1.1;
    gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;
    client_max_body_size 300M;
    rewrite '^/oauth/authorize$' /server/php/authorize.php last;
    rewrite '^/oauth_callback/([a-zA-Z0-9_\.]*)/([a-zA-Z0-9_\.]*)$' /server/php/oauth_callback.php?plugin=$1&code=$2 last;
    rewrite '^/download/([0-9]*)/([a-zA-Z0-9_\.]*)$' /server/php/download.php?id=$1&hash=$2 last;
    rewrite '^/ical/([0-9]*)/([0-9]*)/([a-z0-9]*).ics$' /server/php/ical.php?board_id=$1&user_id=$2&hash=$3 last;
    rewrite '^/api/(.*)$' /server/php/R/r.php?_url=$1&$args last;
    rewrite '^/api_explorer/api-docs/$' /client/api_explorer/api-docs/index.php last;
    location / {
        root /var/www/html/client;
    }
    location ~ '\.php$' {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE 'upload_max_filesize=80M \n post_max_size=120M \n max_execution_time=200 \n max_input_time=200 \n memory_limit=256M';
    }
    location ~* \.(css|js|less|html|ttf|woff|jpg|jpeg|gif|png|bmp|ico) {
        root /var/www/html/client;
        if (-f $request_filename) {
            break;
        }
        rewrite '^/img/([a-zA-Z_]*)/([a-zA-Z_]*)/([a-zA-Z0-9_\.]*)$' /server/php/image.php?size=$1&model=$2&filename=$3 last;
        add_header Cache-Control public;
        add_header Cache-Control must-revalidate;
        expires 7d;
    }
}