block url parameter in nginx

How to Block URL Parameters in NGINX

NGINX is a powerful web server that allows you to control URL access in a fine-grained manner. Sometimes you may need to block URL parameters in NGINX. In this article, we will learn how to do this.


How to Block URL Parameters in NGINX

Here are the steps to block URL parameters in NGINX.


1. Open NGINX Configuration File

Open terminal and run the following command to open NGINX configuration file in text editor.

$ sudo vi /etc/nginx/nginx.conf


2. Block URL Parameters in NGINX

Add the following line to server configuration file to block access through URL parameter q=test at URL www.example.com/product

error_page 418 = @blockAccess;

location /product {
        if ($args ~* "q=test") {
                return 418;
        }
}

location @blockAccess {
        deny all;
}

In the above code, we have added a location block to listen to /product URLs. Within this location block, we have used an if condition to check if the URL parameters, denoted by $args, contains q=test parameter. If so, then NGINX returns response code 418. You can also return 403 Access Denied response code if you want.

Please note, if the URL does not contain the parameter specified above, then it will not be blocked.

Make sure to add the above block before location / block.

If you want to block access through URL parameter q=test for all URLs, modify the above block as shown below.

error_page 418 = @blockAccess;

if ($args ~* "q=test") {
    return 418;
}

location @blockAccess {
    deny all;
}

In this case, we use an if condition outside a location block, so that it is applicable for all requested URLs.

On the other hand, if you want to block access to URL www.example.com/product

error_page 418 = @blockAccess;

# Add before "location /"
location /product {
        return 418;
}

location @blockAccess {
        deny all;
}

This part has nothing to do with URL parameters. It is just in case you want to block a specific URL.

Save and close the file after you add the appropriate code block mentioned above.


3. Restart NGINX Server

Restart NGINX server to apply changes.

$ sudo service nginx restart

In this article, we have seen a few different ways to block URL with parameters in NGINX. You may customize them as per your requirement.

Also read:

How to View Active Connections Per User in MySQL
How to Show All Open Connections to MySQL Database
How to Revoke Privileges for Users in MySQL
How to Show Users with Access to MySQL Database
How to Show User Permissions in MySQL

Leave a Reply

Your email address will not be published.