How to Redirect to Mobile Version of Website in NGINX


redirect to mobile version of website in nginx

If you have a mobile version of your website, it might be a good idea to redirect mobile visitors to it, based on their device. This will allow you to customize your website for mobile users as well as improve user experience. You can easily do it in NGINX with the help of $http_user_agent environment variable. Let us take a look at how to redirect to mobile version of website in NGINX.

 

How to Redirect to Mobile Version of Website in NGINX

Here’s how to redirect to mobile version of website in NGINX.

 

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 User Agent

Let’s say you run a website www.domain.com and want to redirect mobile website visitors to the mobile version of your website m.domain.com based on their user agent value ‘android’, then add the following location block in your NGINX config file.

if ($http_user_agent ~* "^android$") {
   rewrite ^/(.*)$ http://m.domain.com/$1 permanent;
}

 

So your server block will look something like,

server {
  listen 80;
  server_name www.domain.com;
  root /var/www/html;

  # redirect if 'android' is found on the user-agent string
  if ( $http_user_agent ~* 'android' ) {
    return 301 http://m.domain.com$request_uri;
  }

...
}

 

If you want to redirect based on multiple mobile devices (user agent values), use the ‘|’ operator to add more values.

if ($http_user_agent ~* "^(android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos)$") {
   rewrite ^/(.*)$ http://m.domain.com/$1 permanent;
}

 

 

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

 

That’s it! NGINX will automatically redirect all mobile visitors to the mobile version of website. This is a very useful way yo redirect your website visitors to custom content, based on their user agent. You can even use this method to redirect mobile visitors to your mobile website.

 

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!