Blocking a browser with nginx

Blocking a browser with nginx

In this article, we will see how to use nginx to block access to a website based on the browser used by the user.

Blocking access to a website from certain browsers can be necessary for various reasons, such as security, compatibility, or to restrict access to specific content. In this article, we will see how to use nginx to block access to a website based on the browser used by the user.

Web browsers identify themselves with a string called "User-Agent." This string contains information about the browser, the operating system, and other client specifics. To block a browser, we need to identify the corresponding User-Agent.

Here are some examples of User-Agent:

  • Google Chrome: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
  • Mozilla Firefox: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0
  • Microsoft Edge: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.864.64 Safari/537.36 Edg/91.0.864.64

Open your site's configuration file in nginx. This file is usually located in /etc/nginx/sites-available/ or /etc/nginx/conf.d/.

Add the following configuration to block a specific User-Agent:


server {
    listen 80;
    server_name your_domain.com;

    location / {
        if ($http_user_agent ~* "Chrome|Firefox|Edge") {
            return 403;
        }

        # Other site configurations
    }
}

In this example, we are blocking access to the browsers Chrome, Firefox, and Edge. The directive if ($http_user_agent ~* "Chrome|Firefox|Edge") checks if the User-Agent matches any of the specified browsers. If the condition is true, nginx returns an HTTP 403 (Forbidden) status code.

If you want to block only a specific browser, modify the if directive to include only the User-Agent of the browser you want to block. For example, to block only Google Chrome, use:


if ($http_user_agent ~* "Chrome") {
    return 403;
}

Conclusion

Blocking access to certain browsers with nginx is a relatively simple process that requires modifying the server configuration. Using the User-Agent string, we can identify and block specific browsers to ensure that only the desired clients can access our site. Always remember to test changes in a development environment before applying them to production to avoid service interruptions.