Introduction to the ngx_http_browser_module in Nginx
The ngx_http_browser_module module in Nginx is a user-defined module that allows us to identify the type of browser, enabling specific configurations for responding to HTTP requests. In simpler terms, this module determines what type of browser the user is using and based on that decides what type of content to deliver.
In this module, the variable modern_browser_value is used, which indicates whether the browser is modern or not. This capability helps us to potentially deliver different content for older and newer browsers as needed. For example, we can use newer CSS and JavaScript in modern browsers while providing simpler content for older browsers.
Before using this module, it is essential to have enough information regarding how to configure it in Nginx. Here, we will review how to use the modern_browser_value variable and provide an example of it. Additionally, the importance of using such modules in improving user experience and enhancing website performance will be examined.
Let's start with a simple example of configuration and using modern_browser_value. This example will show you how to customize behavior for different browsers using Nginx.
map $http_user_agent $modern_browser_value {
~*Chrome 1;
~*Firefox 1;
~*Safari 1;
default 0;
}
server {
listen 80;
location / {
if ($modern_browser_value) {
return 200 "Modern browser identified";
}
return 200 "Old browser identified";
}
}
Code Explanation
Code:
map $http_user_agent $modern_browser_value {...
In this section, we use the
map
directive to define the $modern_browser_value
variable based on the type of browser user agent detected.Code:
~*Chrome 1;
This line specifies that if the browser is identified as Chrome, then the value 1 will be assigned to
$modern_browser_value
.Code:
default 0;
If none of the above conditions are met, the default value 0 will be assigned to the variable, indicating an old browser.
Code:
if ($modern_browser_value) {...
In this section, using
if
, we verify whether the modern browser has been identified.Code:
return 200 "Modern browser identified";
If the browser is modern, a response indicating a modern browser will be sent to the user.
Code:
return 200 "Old browser identified";
If the browser is identified as old, a different message will be returned to the user.