Execute Command For Each Request on NGINX & Implementation for Simple Nginx Firewall

Simple Nginx Firewall

Using nginx perl module it’s possbile to execute command for each reqeust. In this case i will block target ip if page returns 404.

Install necessary module with sudo apt install libnginx-mod-http-perl

Add following line to /etc/sudoers or add suid bit to ufw

www-data        ALL=(ALL) NOPASSWD: /usr/sbin/ufw

Add following lines to nginx conf located at /etc/nginx/sites-available/mywebsite

	error_page 404 /ban;
	location = /ban {
		perl 'sub {
			my $r = shift;
			my $client_ip = $r->remote_addr;
			my $cmd = "sudo ufw deny from $client_ip";
			system($cmd);
			$r->header_out("Content-Type","text/plain");
			$r->send_http_header();
			$r->print("$client_ip has been blocked.");
			return OK;
		}';
	}

service nginx start

Configure UFW

Allow all incoming requests or allow ports used by nginx.

sudo ufw default allow incoming

Have Fun

Talha