How to fix Netbox nginx Invalid HTTP_HOST header: ‘localhost:13031’. You may need to add ‘localhost’ to ALLOWED_HOSTS.

Problem:

When trying to operate netbox behind an nginx reverse proxy, you see the following log messages:

netbox          | Invalid HTTP_HOST header: 'localhost:13031'. You may need to add 'localhost' to ALLOWED_HOSTS.
netbox          | Bad Request: /

Solution:

Set the Host header in the proxied requests using

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;      
proxy_set_header X-Forwarded-Host $server_name;

in order to tell Netbox which host was originally requested (else, it will assume localhost).

The following location config works fine with Netbox:

location / {
    proxy_pass http://localhost:13031/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;      
    proxy_set_header X-Forwarded-Host $server_name;
    proxy_redirect default;
}

Full config example

server {
    server_name  netbox.mydomain.com;

    location / {
        proxy_pass http://localhost:13031/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;      
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_redirect default;
    }

    listen [::]:443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot


}
server {
    if ($host = netbox.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name  netbox.mydomain.com;

    listen [::]:80; # managed by Certbot
    return 404; # managed by Certbot
}