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.
access_log/error_logwork with variables, but with some limitations.server_namecan't contain variables. – Alexey Ten Nov 17 '14 at 11:38$hostname. Updated the answer to clarify that behaviour. – Xavier Lucas Nov 17 '14 at 12:10$hostnameis the only allowed variable. https://github.com/nginx/nginx/blob/bb8c0683da773566e09797ef8a4ee00ad1e0f956/src/http/ngx_http_core_module.c#L4370 Actually, it's more like a magic constant, not a real variable – Alexey Ten Nov 17 '14 at 12:12*_logs work with variables, but nginx's worker should have permissions to create resulted filename. In particular that means all previous directories must exist. – Alexey Ten Nov 17 '14 at 12:17http.serverblock and use it in theproxy_passyou cannot set a custom variable in astream.serverblock. – Jesse Chisholm Sep 18 '20 at 02:45