Apache2: How to Redirect Users to Mobile or Normal Web Site Based on Device Using mod_rewrite

Since the massive rise of smartphones and tablets like the iPhone, iPad, Android phones and tablets, BlackBerries, etc. you might have considered creating a mobile version of your web site. This tutorial explains how to configure Apache to serve the mobile version of your website if the visitor uses a mobile device and the regular version if the visitor uses a standard desktop PC. This can be achieved with Apache's rewrite module.

1 Preliminary Note

In this tutorial, my "normal" website is accessible under http://www.example.com and http://example.com, while my mobile site is called http://m.example.com. These vhosts already exist on my system, so I'm not going to cover how to set them up.

2 Enabling mod_rewrite

First, you must ensure that the Apache module mod_rewrite is enabled. This module allows you to do an httpd redirect, apache redirection, and apache rewrite URL via an apache web server. On Debian/Ubuntu, you can enable it like this:

a2enmod rewrite

Restart Apache afterwards - for Debian/Ubuntu, the command is:

/etc/init.d/apache2 restart

 3 Configuring Apache To Allow Rewrite Rules In .htaccess Files

My "normal" web site www.example.com/example.com has the vhost configuration file /etc/apache2/sites-available/www.example.com.vhost and the document root /var/www/www.example.com/web.

My mobile site m.example.com has the vhost configuration file /etc/apache2/sites-available/m.example.com.vhost and the document root /var/www/www.example.com/mobile.

I want to place the rewrite rules for each site in an .htaccess file (although it is also possible to place them directly in the vhost configuration file) with get read by apache http server. Therefore I must first modify our vhost configurations so that both .htaccess files can contain rewrite directives. We can do this with the line AllowOverride All (which allows .htaccess to override all settings in the vhost configuration, the server configuration):

vi /etc/apache2/sites-available/www.example.com.vhost
[...]
        <Directory /var/www/www.example.com/web/>
                AllowOverride All
	</Directory>
[...]
vi /etc/apache2/sites-available/m.example.com.vhost
[...]
        <Directory /var/www/www.example.com/mobile/>
                AllowOverride All
        </Directory>
[...]

Restart Apache afterward:

/etc/init.d/apache2 restart

 4 Creating Rewrite Rules

Now let's create the rewrite rules for the "normal" website www.example.com/example.com that will redirect all users of mobile devices to the mobile version m.example.com - I focus on the relevant devices/user agents here, which are Android, Blackberry, Googlebot-mobile (Google's mobile search bot), IE Mobile, iPad, iPhone, iPod, Opera Mobile, PalmOS, and WebOS.

The /var/www/www.example.com/web/.htaccess file looks as follows:

vi /var/www/www.example.com/web/.htaccess
<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://m.example.com/ [L,R=302]
</IfModule>

For our mobile web site m.example.com, the rewrite rules that redirect all users that don't use a mobile device to our "normal" web site www.example.com/example.com look as follows - I've negated the RewriteCond condition from the previous .htaccess file:

vi /var/www/www.example.com/mobile/.htaccess
<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://www.example.com/ [L,R=302]
</IfModule>

That's it, we set up our redirect directive! Now you can do some testing, e.g. visit m.example.com with a standard desktop browser:

If all goes well, you should be redirected to www.example.com:

Now test with a mobile device (I use an Android phone here) and go to www.example.com:

You should be redirected to m.example.com:

 

Share this page:

Suggested articles

13 Comment(s)

Add comment

Comments

By: Anonymous at: 2011-09-12 07:15:32

Please don't do this without a way of giving the visitor to your site the option to override. Tablets are as capable as desktops and it's very frustrating when you're stuck viewing a cut-down site designed for a 3 or 4 inch screen on a device with a 10 inch screen.

By: Anonymous++ at: 2011-10-07 19:55:47

Anonymous is right.  Forcing this on the user is like a cafe that checks what kind of cup you brought in and gives you the drink they think best fits your container. Maybe I like tea in my coffee mug (or hot cocoa with cinnamon).  Better to let me decide, and when I come back next time (because of your friendly service and nice tea), ask me briefly, "the usual?" I should always have the option to change my mind, don't nag, just give me choices and remember me from last time if at all possible.

 

By: Marco Garcia at: 2012-04-20 15:08:21

Yes! It´s true. 

And i´ve been such a time frustrated with all the m.site. I got a Xoom Tablet with Android 3 and became less frustrated when i discovered that the Opera 5 Navigator could simulate a desktop connection. There´s an option to choose between tablet and desktop mode. I agree that Tablets has the same power that most netbooks and the main difference is that netbooks are more suited to editing uses while tablets are more suited to viewing.

By: Anonymous at: 2011-09-25 05:10:53

Great tutorial - I have tried this on a website under construction and it works as expected for Iceape as well as for HTC smartphone. However I do agree with the previous comment - iPads have 1024x768 px screens so should (?) display standard web pages correctly and may have to be excluded from the list of small devices. A problem may arise with Android which could be used for smart phones as well as for tablets. Not sure if this is workable other than by excluding Android as well, and provide a link at top of page to the small-screen pages. In which case every device could be provided with the choice, but necessitates small-screen devices downloading unsuitable pages initially.

By: Oliver Ponder at: 2011-11-15 19:31:56

The lines that are like:

RewriteRule ^$ http://m.example.com/ [L,R=302]

Feature a matcher that will never match anything.

It should be something like

RewriteRule ^/(.*) http://m.example.com/ [L,R=302]

or

RewriteRule ^(.*)$ http://m.example.com/ [L,R=302]

By: idel at: 2012-02-01 23:15:54

I think the best way to redirect mobile is with "Apache Mobile Filter" an open source and free project below an example:

PerlSetEnv AMFMobileHome /usr/local/AMF
PerlSetEnv AMFProductionMode true
PerlSetEnv ServerMemCached localhost:11211
PerlTransHandler +Apache2::AMFLiteDetectionFilter
RewriteEngine on
RewriteCond %{ENV:AMF_ISMOBILE} ^true*
RewriteRule ^(.*)$ http://m.foo.org [R=301,L]

you can also use AMFDetectRightFilter, AMF51DegreesFilter or AMFWURFLFilter is depend of which device repository you want to use.

For more detail: http://www.apachemobilefilter.org

By: Mallak85 at: 2012-11-15 08:38:26

I found the codes in this page the most useful. You guys rock! I was finally able to get my site to recognize mobile devices, and redirect them over to a mobile site, I created. However, I have one question. For tablets, like the HP TouchPad, which ALSO runs on WebOS, I'm thinking I may want to create a link that would disable this redirect, but I can't think of how to code this. Can anybody provide me any input as to how I might incorporate a link on my mobile webpage, that if clicked, will bypass this redirect and take them directly back to my non-mobile optimized site?

By: Vigram K at: 2013-01-04 07:12:46
By: Android Developer at: 2015-03-24 15:53:55

thanks for the info

By: Idel at: 2015-09-10 08:13:00

Just an update of AMF now there is apache module mod_amf that do easily this work.

Apache Modules

By: Benjamin E. Nichols at: 2015-10-27 05:44:03

Looks like somebody screwed up this article, the user agents are the same for both htaccess files?? LOL that makes no sense!

By: johndburger at: 2015-12-22 13:05:47

The list of agents is the same, but one of the conditions starts with bang and the other doesn't. The conditions match in exactly conplementary situations.

By: r k singh at: 2017-09-14 08:48:44

above code is not working...