Pascal Klein
Pascal Klein

Reputation: 24913

How to rewrite to mobile.myUrl.com if user is mobile? (use Apache or inside Webapp?)

If a user is viewing my Website www.myUrl.com with a mobile Browser, I would like to redirect them to mobile.myUrl.com. I read this thread Auto detect mobile browser (via user-agent?), which says, that you should detect the user-agent and then redirect the user.

But I havent found a thread, which tells me HOW to redirect to mobile.myUrl.com. Should and can I use Apache for that? Or should I instead do it inside my Webapp?

Upvotes: 0

Views: 5007

Answers (1)

Evan Mulawski
Evan Mulawski

Reputation: 55354

JAVASCRIPT

First, let me point out that most mobile devices have the ability to disable Javascript.

Now, the most common form of redirection for mobile devices is through Javascript. (Apple's website uses this method.) When the page begins to load, a script is run to determine the User Agent, a browser-specific (and os-specific) string that details the browser type, device type, and/or operating system. This string is then matched against known mobile devices. For example:

<script language=javascript>
<!--
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
   location.replace("http://mobile.myurl.com");
}
-->
</script>

This script would redirect any browser with a user agent containing "iPhone" or "iPod" to "mobile.myurl.com".

This would need to be checked for a bunch of other devices.

Check this site for more information:

http://www.hand-interactive.com/resources/detect-mobile-javascript.htm

If you are using a PHP-compatible server, see this site:

http://www.hand-interactive.com/resources/detect-mobile-php.htm

APACHE

Simply using the mod_rewrite engine, you can redirect browsers with specific user agent strings, just like the Javascript method above:

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{HTTP_USER_AGENT} iPod
RewriteRule .* http://mobile.myurl.com/ [R]

This checks for "iPhone" and "iPod" users and redirects them to a mobile version of the site.

More here:

http://www.themepremium.com/htaccess-code-http_user_agent-of-multiple-phone-browsers-for-wordpress-blogs/

Upvotes: 3

Related Questions