How to Redirect Based on Web Browser in NGINX


redirect based on web browser nginx

Some browsers support advanced features such as CSS3 animation and HTML5 that others don’t. To ensure that your website works on legacy browsers as well as makes use of advanced features in modern browsers, you can redirect users to different pages, based on their web browsers. This will provide a better user experience. Let us take a look at how to redirect based on web browser in NGINX.

 

How to Redirect Based on Web Browser in NGINX

Here are the steps to redirect based on web browser in NGINX. We will use NGINX environment variable HTTP_USER_AGENT to determine the web browser for each request, and redirect users based on their web browser values.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Redirect based on web browser

Let’s say you have a web page http://example.com/webpage.html but you want to redirect chrome users to http://example.com/webpage-chrome.html, firefox users to http://example.com/webpage-firefox.html and IE users to http://example.com/webpage-ie.html

So we will add an if condition in our server block that checks $http_user_agent variable redirects users to different pages


location /webpage.html {

if ($http_user_agent ~* "^.*Firefox.*$") {
  return 301 https://example.com/webpage-firefox.html;
}

if ($http_user_agent ~* "^.*Chrome.*$") {
  return 301 https://example.com/webpage-chrome.html;
}

if ($http_user_agent ~* "^.*Trident.*$") {
  return 301 https://example.com/webpage-ie.html;
}

...#configuration for non-redirected pages

}

location /webpage-firefox.html {

...

}

location /webpage-chrome.html {

...

}

location /webpage-ie.html {

...

}

...

 

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

Now NGINX will check the $http_user_agent for each request and redirect users based on their web browser.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!