Nginx access control / GeoIP

cat <<EOF> /etc/nginx/conf.d/geoip.conf 
geoip_country /usr/share/GeoIP/GeoIP.dat;
 
map $geoip_country_code $allowed_country {
    default no;
    DE yes;
    CH yes;
}
 
log_format allow "allow $remote_addr;";
EOF
chmod 644 /etc/nginx/conf.d/geoip.conf
 
 
cat <<EOF> /usr/local/bin/nginx-allow
#!/bin/bash
 
while inotifywait --quiet --event create,delete --exclude "[^c][^o][^n][^f]$" /tmp
do
    /usr/sbin/nginx -t && /usr/sbin/service nginx reload
done
EOF
chmod 755 /usr/local/bin/nginx-allow
 
 
cat <<EOF> /etc/systemd/system/nginx-allow.service
[Unit]
Description=Nginx configuration monitor service
After=nginx.service
 
[Service]
Type=simple
ExecStart=/usr/local/bin/nginx-allow
Restart=on-abort
 
[Install]
WantedBy=multi-user.target
EOF
chmod 644 /etc/systemd/system/nginx-allow.service
 
 
systemctl daemon-reload
systemctl enable nginx-allow.service 
systemctl start nginx-allow.service 
 
 
 
cat <<EOF> /etc/cron.hourly/clean_nginx_allow
#!/bin/bash
 
find /tmp -ctime +2 -name nginx_allow_*.conf -delete
EOF
 
 
cat /etc/nginx/sites-available/nginx-allow
...
set $backend $scheme://10.0.10.101;
error_page 403 =404 /404.gif;
 
location /nginx-allow/ {
    if ($allowed_country = yes) {
        access_log /tmp/nginx_allow_$remote_addr.conf allow;
        proxy_pass $backend;
    }
 
    proxy_pass $backend/404.html;
}
 
location ~ ^(/wp-admin|/admin) {
    include /tmp/nginx_allow_*.conf;
    deny all;
 
    proxy_pass $backend;
}
...
 
cat <<EOF> /root/bin/nginx_allow_ddns.sh
#!/bin/bash -e
 
DDNS=foo.dyndns.com
 
sleep 3
 
IP=$(getent hosts ${DDNS} | cut -d" " -f1)
[ -n ${IP} ] && echo "allow ${IP};" > /tmp/nginx_allow_${IP}.conf
 
service nginx reload
EOF
 
# crontab -e
@reboot /root/bin/nginx_allow_ddns.sh

Links
https://docs.nginx.com/nginx/admin-guide/mail-proxy/mail-proxy/
https://docs.nginx.com/nginx/admin-guide/security-controls/controlling-access-by-geoip/
https://www.justinsilver.com/technology/linux/nginx-configuration-monitor/
https://guides.wp-bullet.com/auto-whitelist-dynamic-dns-address-nginx-security/
https://mensfeld.pl/2014/08/nginx-block-access-to-certain-parts-of-your-app-based-on-visitor-country/
http://www.mylinuxtips.info/linuxtipstutorials/webservers/how-to-block-countries-on-nginx-with-geoip-module/
https://www.digitalocean.com/community/tutorials/how-to-use-nginx-s-map-module-on-ubuntu-16-04