How can I use apache to redirect users (based on user_agent and using mod_rewrite) to my mobile site only if a mobile pages exists.

I want to detect mobile users based on their user_agent.

If a user is browsing the full version of the site and they have a certain user_agent, I want to redirect them (using mod_rewrite) to the mobile site - if the mobile page exists.

Full site URL example http://www.domain.com/page1.html Equivalent mobile site URL example (note .htm instead of .html) http://m.domain.com/page1.htm

I need to do this with apache and not something like php

Bonus: The mobile site could have links to the full site (if the page doens't have a mobile equilelant) and I want to keep redirecting people and I want to continue the redirection unless people click on a "Full Site" link which will opt them out of redirection via a url parameter - ex: ?ver=ful


I'll have a stab.

In the full site vhost:

RewriteCond %{HTTP­_US­ER_­AGENT} Some-Mobile-UA [OR]
RewriteCond %{HTTP­_US­ER_­AGENT} Some-Other-Mobile-UA [OR]
RewriteCond %{HTTP­_US­ER_­AGENT} Yet-Another-Mobile-UA [OR]
RewriteCond %{HTTP­_US­ER_­AGENT} The-Final-Mobile-UA
RewriteCond /var/www/mobile%{REQU­EST­_URI} -f
RewriteCond %{HTTP­_CO­OKIE} !stayOnFullSite
RewriteRule /(.*)l http://m.domain.com/$1 [R]

And in the mobile site vhost:

RewriteCond %{QUER­Y_S­TRING} ver=full
RewriteRule ^ - [CO=stayOnFullSite:true]

RewriteCond %{REQU­EST­_FI­LENAME} !-f
RewriteCond /var/www/html%{REQU­EST­_URI}l -f
RewriteRule /(.*) http://www.domain.com/$1l [R]

Notes:

I've rather crudely chopped the trailing "l" off .html when redirecting to the mobile site and added it back on when redirecting back.

I also chopped it off when checking that the file exists on the main site but I can't figure out how to remove it when checking that the file exists on the mobile site. Possibly another RewriteCond in front of it that matches all but the final "l" in %{REQUEST_URI} and then use %1 in the following RewriteCond like this:

RewriteCond %{REQU­EST­_URI} (.*)l
RewriteCond /var/www/mobile%1 -f

It might be easier to standardise your site on a single file extension.

You can set the rest of the available cookie parameters. Details are in the mod_rewrite docs and the section on flags.

This configuration is completely untested.


Look Apache Mobile Filter is free, easy to install and to configured. Here is an example:

#Configuration AMF Filter
#
PerlSetEnv AMFMobileHome /usr/local/AMF
PerlSetEnv AMFProductionMode true
PerlSetEnv ServerMemCached localhost:11211

PerlTransHandler +Apache2::AMFLiteDetectionFilter
RewriteEngine on
RewriteCond %{ENV:AMF_DEVICE_IS_MOBILE} ^true*
RewriteRule ^(.*)$ http://m.foo.org [R=301,L]

Let me know