How to Redirect based on Browser Language in NGINX


nginx redirect based on browser language

If your website attracts visitors from various countries, then you might want to redirect them to language-specific web pages to provide a better user experience. You can easily do it in NGINX using the “Accept Language” Module. Let us take a look at how to redirect based on browser language in NGINX.

 

How to Redirect based on Browser Language in NGINX

Here’s how to redirect based on browser language in NGINX.

 

1. Install NGINX Accept Language module

Open terminal session or SSH into your Linux system and run the following command to install the “Accept Language” module in NGINX.


$ sudo apt-get install nginx-extras

 

 

2.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

 

3. Redirect based on browser language

Let’s say you run a website www.example.com and have created separate websites at /en, /fr and /es for english, french and spanish visitors.

So you can simply add a rewrite directive in your location block, that will check the “Accept Language” value and redirect visitors


location / {
  rewrite (.*) $1/$http_accept_language;
}

 

If the above method doesn’t work for you, use a map directive to set a server variable, $lang, and use its value to redirect to language-specific sites.

map $http_accept_language $lang {
        default en;
        ~es es;
        ~fr fr;
}

...

rewrite (.*) $1/$lang;

 

 

 

4. 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 automatically redirect based on users’ browser language.

 

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!