You can do this using docker!
As far as I can tell, this is a feature of the docker image Nginx puts out, but it might also be a feature of docker itself. I'm sure someone will correct me. However, I know that it works with docker, so that's what I'll propose.
Nginx regularly updates a docker file on the docker image hub. The image they put out allows you to create "template" files that basically pass whatever variable you want into your conf file.
For example, let's say I want my conf file to look like this:
http {
server {
server {
# Redirect http to https
listen 80;
listen [::]:80;
server_name www.example.com example.com;
root /etc/nginx/www;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
}
What you do is create a "template" file default.conf.template
in /etc/nginx/templates
(you can actually configure this if you want) that looks like this:
http {
server {
server {
# Redirect http to https
listen ${NGINX_PORT};
listen [::]:${NGINX_PORT};
server_name www.${NGINX_HOST} ${NGINX_HOST};
root ${NGINX_ROOT};
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
}
Then, you create a docker-compose.yml
file (you can do this from command line as well, but it's not going to look as pretty) that looks like this:
services:
web:
image: nginx:latest
volumes:
- /etc/nginx/templates:/etc/nginx/templates:ro
- /etc/nginx/www:/etc/nginx/www:ro
ports:
- "8080:80"
environment:
- NGINX_HOST=example.com
- NGINX_PORT=80
- NGINX_ROOT=/etc/nginx/www
And run it by simply starting docker compose:
docker compose up -d
Check that the container is running with docker container list
You can verify the conf file was evaluated correctly by copying the file out of the running container if you want like so (double check the container name here, from the previous command): docker cp docker-web-1:/etc/nginx/conf.d/default.conf . && cat default.conf
As far as I can tell, you can use as many environment variables as you want.