• Home
  • Blog
  • Nginx Security - Allow certain IP(s) and deny everything else

Nginx Security - Allow certain IP(s) and deny everything else

Deny all except certain IP(s)!

All this is put into the file: /etc/nginx/sites-available/example.com which is symlinked to the sites-enabled folder

# Set the 403 (forbidden page)
error_page 403 = @denied;

# Allow certain IP and deny all others (can use subnets, see Nginx docs).
# This block goes down the list until it finds a match, then executes the try_files part.
location / {
	allow 192.168.22.10;
	allow 192.168.22.1;
	deny all;

	# You can change this to use index.php?$query_string like normal.
	try_files $uri $uri/ @allowed;
}

# This is the handler for the try_files above.
# Just showing you can return anything.
location @allowed {
	default_type text/html;
	echo 'Allowed via $REMOTE_ADDR';
}

# This is the handler for 403 error_page, set above.
location @denied {
	default_type text/html;
	echo 'Denied via $REMOTE_ADDR';

	# Can enable a redirect elsewhere
	#return 301 http://example.com/soon
}

About the Author

Ben Sampson

Ben Sampson

Vegan • PHP Developer • PC Gamer • Love to code • Debian / macOS user

Comments