Home > Back-end >  How to make nginx listen only on non-local DHCP IP(s)?
How to make nginx listen only on non-local DHCP IP(s)?

Time:11-14

I'm using nginix on my raspberry Pi to mirror a local python web websocket service (127.0.0.1:80) out over the rPI's lan IP(s) - e.g. 192.168.1.20 and 2001:7000:1111:6d11:124f:1192:1214:134.

DHCP supplies my lan IPs (and might even be an internet IP - I've got 5 real ones I can use). I must use SSL (CORS/JS etc rules...) and so must redirect external :80 to :443

So I need to replace this:-

server {
    listen 192.168.0.20:80;
    server_name rpi.ssrve.com;
    return 301 https://$host$request_uri;
}

because each time I reboot, the .20 is something else, so nginix bombs and never comes up after reboot. I obviously can't use 0.0.0.0 - because 127.0.0.1:80 is already (or will soon be after the service starts at boot) listening

Is there some kind of magic alias like "nonlocalhost" or "*-lan" or something, that I can put in place of my hardcoded "192.168.0.20" so nginix just uses the right IP(s) by itself?

Something logically like " { * not 127.0.0.1 }:80 " basically ?

I assume everything else will work fine after that - I've got these:-

   server {
        ssl on;
        listen 443;
        # etc
   }
   location /ws {
        proxy_pass http://127.0.0.1:5678/ws;
        # etc
   }
    location / {
        proxy_pass http://127.0.0.1;
    }

which behave fine, and already don't make me put IPs in there (which is OK, since nothing is already on port 443, so "0.0.0.0" (which I assume is the default when no IP is given) has no clash there)

CodePudding user response:

Here is a workaround to put into /etc/rc.local

perl -i -npe 's/(listen\s )(\d \.\d \.\d \.\d )(.*FIX_LANIP)/$1$::ip$3/ if($::ip); BEGIN{while($n  <60){$::ip=`/home/pi/bin/get_local_addr.py`; chomp($::ip); $::ip="" unless($::ip=~/^\d/); if($::ip){$n=99}else{sleep 1}}}' /etc/nginx/sites-available/default

systemctl restart  nginx.service

The above reads your setup, finds the line(s) you have marked by adding #FIX_LANIP comment on the end of, and fixes the current IP into them

Assumes get_local_addr.py from https://gist.github.com/gitcnd/7f27a319e3dcd79c610311f666d02b88

Example input line from /etc/nginx/sites-available/default :-

# Redirect external HTTP requests to external HTTPS 
server {
    listen 192.168.1.210:80;      # FIX_LANIP
    server_name rpi.local;
    return 301 https://$host$request_uri;
}

It also sleeps for upto 1 minute, to give your wifi time to connect and get an IP address...

  • Related