How can I use environment variables in Nginx.conf

Better Stack Team
Updated on November 23, 2023

You can use environment variables in your Nginx configuration (nginx.conf) by making use of the env module and the set directive. Here's how you can do it:

Step 1 -Install the nginx with env module

First, make sure you have Nginx installed with the ngx_http_env_module module. You can check if your Nginx installation includes this module by running:

 
nginx -V 2>&1 | grep ngx_http_env_module

If you don't see any output, you might need to recompile Nginx with the module enabled or install a version of Nginx that includes it.

Step 2 - Set Environment Variables

Define the environment variables you want to use in your Nginx configuration. You can do this in various ways, depending on your server environment. For example, you can set them in your system environment or use a tool like systemd's Environment directive for systemd service units.

Step 3 - Modify Your Nginx Configuration

Open your nginx.conf file and use the set directive to assign values to variables using the env module. Here's an example of how you can use an environment variable:

 
http {
    server {
        location / {
            set $my_variable $MY_ENV_VARIABLE;
            # Now, you can use $my_variable in your configuration.
            # For example, in a proxy_pass directive:
            proxy_pass http://$my_variable;
        }
    }
}

In this example, the environment variable MY_ENV_VARIABLE is assigned to the Nginx variable $my_variable.

Step 4 - Reload or Restart Nginx

After modifying your Nginx configuration, you need to reload or restart Nginx for the changes to take effect.

 
sudo systemctl reload nginx

Now, Nginx will use the value of the environment variable MY_ENV_VARIABLE in your configuration.

Make sure the environment variable is set and accessible to the user running the Nginx process. The exact method for setting environment variables may vary depending on your operating system and deployment environment.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github