M
M
mashincode2020-07-07 17:28:56
Nginx
mashincode, 2020-07-07 17:28:56

How to create dynamic server_name in nginx configs?

I deploy my Django projects through Docker and use the same nginx config, the problem is that I need to specify server_name in the server directive and this is always the ip address of the server on which I work, how can I automate this process so that the server_name is automatically pulled up, here is an example config

server {

    listen 443 ssl;
    listen [::]:443 ssl;

    server_name МОЙ IP тут;
    access_log  /var/log/nginx/example.log;
    server_tokens off;

    location /static/ {
        autoindex off;
        alias /static/;
    }

    location /media/ {
        autoindex on;
        alias /media/;
    }

    location / {
        try_files $uri $uri/ @python_django;
    }

    location @python_django {
        proxy_pass http://python:8000;
        proxy_pass_request_headers on;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
    }
}

server {

    listen 80;
    listen [::]:80;

    server_name МОЙ IP тут;

    return 301 https://$server_name$request_uri;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
ky0, 2020-07-07
@ky0

Use the directive default_server, then it won't matter what your IP is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question