Skip to content

Instantly share code, notes, and snippets.

@mikeyhill
Created December 10, 2015 08:11
Show Gist options
  • Save mikeyhill/0e046ab9a3a5216944c9 to your computer and use it in GitHub Desktop.
Save mikeyhill/0e046ab9a3a5216944c9 to your computer and use it in GitHub Desktop.
Javascript, PHP and .htaccess redirect for mobile users
This is a simple way to redirect based on screen size. This redirect would go at the bottom of your template for the landing page.
<br />
&lt;script&gt;// &lt;![CDATA[<br />
if (screen.width &lt;= 800) {<br />
document.location = &quot;http://subdomain.domain.com&quot;;<br />
}<br />
// ]]&gt;&lt;/script&gt;<br />
OR
<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://subdomain.domain.com";
}
//-->
</script>
--------------------------
PHP Method
You can place this anywhere in your landing page template (or if you have a wrapper template, in your header somewhere)
<?php
$iphone = strpos($_SERVER[‘HTTP_USER_AGENT’],”iPhone”);
$android = strpos($_SERVER[‘HTTP_USER_AGENT’],”Android”);
$palmpre = strpos($_SERVER[‘HTTP_USER_AGENT’],”webOS”);
$berry = strpos($_SERVER[‘HTTP_USER_AGENT’],”BlackBerry”);
$ipod = strpos($_SERVER[‘HTTP_USER_AGENT’],”iPod”);
if ($iphone || $android || $palmpre || $ipod || $berry == true)
{
echo “<script>window.location=’http://subdomain.site.com'</script>”;
}
?>
-------------
.htaccess Method
This will only work if you are using Apache, however, there is a similar method if you are using nginx or lighttpd
RewriteEngine On
# Check for mime types commonly accepted by mobile devices
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ http://m.domain.com%{REQUEST_URI} [R,L]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment