How to Redirect to Mobile Version of Website in Apache


redirect to mobile website in apache

If you have users who visit your website via mobile devices, then it might be a good idea to redirect them to the mobile version of your website when they visit via mobile. This allows you to customize website content for mobile users and improve user experience. You can easily accomplish it in Apache web server with the help of mod_rewrite module and HTTP_USER_AGENT environment variable. Let us take a look at how to redirect to mobile version of website in Apache.

 

How to Redirect to Mobile Version of Website in Apache

Here are the steps to redirect to mobile version of website in Apache. We will basically use the environment variable HTTP_USER_AGENT to determine the user device and redirect them to the mobile website.

Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:

 

Place your .htaccess file in the root document folder of your website (/var/www/html)

 

1. Open .htacces file

Open your .htaccess file in a text editor.


$ sudo vim /var/www/html/.htaccess

 

2. Redirect to mobile website

Let’s say you want to redirect android visitors to your mobile website m.domain.com based on a specific user agent “android”, then add the following code to your .htaccess file.


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule ^$ http://m.domain.com/ [L,R=302]
</IfModule>

The above code will redirect visitors based on the value of a server variable called HTTP_USER_AGENT.

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


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos" [NC]
RewriteRule ^$ http://test.domain.com/ [L,R=302]
</IfModule>

The above code will redirect visitors for multiple user agents.

The above code will only redirect temporarily. If you want to redirect permanently, then use ‘301’ instead of ‘302’ above.

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! Now Apache will automatically redirect mobile-based website visitors based on their user agent values. Redirecting visitors to mobile devices allows you to provide a more personalized user experience for your website and even show custom content.

 

 

 

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!