Nginx redirect without a server name

Alex Loper asked:

I’m serving a webpage from an embedded linux box that may or may not be connected to the internet. The idea is, a user enters the IP of the machine and the page comes up. I want to redirect all non-ssl urls to an ssl url (https). Every example I’ve found uses $server_name or $host in the return line of the nginx configuration. The problem for me is that the IP of the machine might change and editing the nginx config file every time is not an option. I’ve tried setting the server_name to _ to no avail. What does work is if I set server_name to the current IP of the machine. Then, if I type in it redirects to, which is what I want. Unfortunately this will not work in production, since as mentioned the IP may change. My current nginx config is below.

server {
    listen       80;
    #server_name  _;
    ssl_certificate server.crt;
    ssl_certificate_key private.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;
    autoindex on;
    return 302 https://$server_name/dashboard;

    location /dashboard {
        alias build;
        index index.html;

My answer:

Then it’s $host that you want to use, because this is what contains the Host: header that the browser supplied.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.