DEV Community

aakhtar3
aakhtar3

Posted on

Dynamic and Abstract Nginx

Dynamic and Abstract Nginx

Nginx is a powerful webserver and can built dynamically by injecting environment variables with envsubst and importing modular configs with the include directive.

envsubst

input/output

  • Create /etc/nginx/nginx.conf.template with environment variables ${VAR}
  • Use envsubst to dynamically generate a new /etc/nginx/nginx.conf
# Define the environment variables
export SERVER='example' LOG='example'

# Run command to generate new nginx.conf
cd /etc/nginx
envsubst '${SERVER},${LOG}' < nginx.conf.template > nginx.conf
Enter fullscreen mode Exit fullscreen mode
brew install

Mac users will need to install gettext which includes envsubst.

brew install gettext
brew link --force gettext 
Enter fullscreen mode Exit fullscreen mode

Include

From the example above using the sample http config.

* is a wildcard and will match on example.com.conf.

http {
    ...
    include /etc/nginx/conf.d/example.*.conf;
    ...
}
Enter fullscreen mode Exit fullscreen mode

Here is an example folder structure for your Nginx modules.

/etc/nginx/
    nginx.conf                  # HTTP
    /conf.d                     # Server(s)
        example.com.conf        # Can contain multiple servers
        default.conf            # Comes with nginx
        *.conf
    /sites-enabled              # Includes
        /location               # Location Includes
            assets.inc          # /location blocks to static assets
            *.inc
        /SSL                    # SSL Includes
            example.com.inc     # Contains SSL directives for example.com
            *.inc
        /*                      # You can continue to modularize your code base
            *.inc
Enter fullscreen mode Exit fullscreen mode

Check out this repo which has more include examples.

GitHub logo 10up / nginx_configs

ARCHIVED: Nginx Configuration Template for WordPress Sites

Top comments (2)

Collapse
 
suther profile image
Samuel Suther

Thanks for your post, it guide me in the right direction.

But what's heavily missing is where you show, what exactly to put into /etc/nginx/nginx.conf.template.
Do you only put:

${SERVER}
${LOG} 
Enter fullscreen mode Exit fullscreen mode

in there?

A hint for those who need to execute this envsubst-command via sudo:

Use sudo -i, else you'll got an error like this: -bash: nginx.conf Permission denied

Collapse
 
aakhtar3 profile image
aakhtar3

Yes, you put the variable reference in the template.

You need to have the variables defined in scope before interpolating and generating the final config.