Alternate and Other Automatic Redirection Scripts

Overview

On this page, you will find many of different codes to redirect your site. By default, the JavaScript redirect code is provided to embed directly into your original website's HTML, but also use server side options to set up the redirect.

Client Side Redirect using JavaScript

This method is the easiest to install. Simply paste the JavaScript code below into the head tag of your HTML page, and replace in the code the " http://m.example.com " with your mobile website domain (including http://).

<script src="http://static.mobilewebsiteserver.com/redirect.js" type="text/javascript"></script>
<script type="text/javascript">
   DM_redirect("http://m.example.com");
</script>
Note: some mobile devices like old blackberry models don't support JavaScript, if you would like to support those devices as well, you will need to use server-side redirection
 

Redirect using server side snippet

The server-side method might be more complex to implement but will ensure that mobile devices that do not support JavaScript are supported as well. Below are code examples for PHP, ASP and JSP. Please replace the place holder " http://m.example.com" in the code with your mobile website domain (including http://).

PHP

Paste the code below in the very beginning of yourindex.php file. Be sure to edit the m.example.com with your own mobile URL.

<?php
$mobileDomain = "http://m.example.com";
$no_redirect = @$_REQUEST['no_redirect'];
if($no_redirect != "true")
{
    $agent = @$_SERVER['HTTP_USER_AGENT'];
    @ini_set('default_socket_timeout',1);
    $handle = @fopen("http://m.mobilewebsiteserver.com/api/public/detect?ua=" . urlencode($agent), "r");
    @stream_set_timeout($handle, 1);

    /* check if we should redirect*/
    $result = @fread ( $handle , 1 );

    @fclose($handle);
    if ($result == "y") {
        $currenturl = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $mobileUrl = $mobileDomain ."?url=" .urlencode($currenturl);
        $mobileUrl=$mobileUrl."&dm_redirected=true";
        header("Location: ".$mobileUrl);
        exit;
    }
}
?>

ASP

Paste the code below in the very beginning of your index.asp file. Be sure to edit the m.example.com with your own mobile URL.

<%Dim no_redirect, detecturl, handle, output, currenturl, mobileUrl
no_redirect = Request.QueryString("no_redirect")
If no_redirect <> "true" Then
currenturl = ( "http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL") ) & "?" & Request.ServerVariables("QUERY_STRING")
detecturl = "http://m.mobilewebsiteserver.com/api/public/detect?ua=" & Server.UrlEncode(Request.ServerVariables("HTTP_USER_AGENT"))
set handle = CreateObject("MSXML2.ServerXMLHTTP")
handle.setTimeouts 5000,5000,5000,5000
handle.open "GET", detecturl, false
handle.send ""
output = handle.responseText
mobileUrl = "http://m.example.com" & "?url=" & Server.UrlEncode(currenturl) & "&dm_redirected=true"
If output = "y" Then
Response.Redirect(mobileUrl)
End If
End If
%>

JSP

Paste the code below in the very beginning of your index.jsp file. Be sure to edit the m.example.com with your own mobile URL.

<%@page import="java.net.URLEncoder"%>
<%@page import="java.net.URL"%>
<%@page import="java.net.HttpURLConnection"%>
<%
if(! "true".equals(request.getParameter("no_redirect")))
{
String currenturl = request.getRequestURL() + (request.getQueryString() != null ? "?" + request.getQueryString() : "");
try{
String ua = URLEncoder.encode(request.getHeader("user-agent"), "utf-8");
HttpURLConnection con = (HttpURLConnection)new URL("http://m.mobilewebsiteserver.com/api/public/detect?ua=" + ua).openConnection();
con.setConnectTimeout(5000); //set timeout to 5 seconds
char c = (char)con.getInputStream().read();
con.disconnect();
if(c == 'y')
{
String mobileUrl = "http://m.example.com";
response.sendRedirect(mobileUrl + "?url=" + URLEncoder.encode(currenturl) + "&dm_redirected=true");
}
}
catch(Exception e){
e.printStackTrace();
}
}
%>

.htaccess (Advanced)

Install the following code at the bottom of your existing .htaccess file. Please be sure to backup your existing .htaccess file before you make changes. Installing the .htaccess code incorrectly can bring down your website easily. Make sure you replace any reference of example.com with your own domain.

RewriteEngine on
######### Set cookie for users who return to desktop site
RewriteBase /
RewriteCond %{QUERY_STRING} no_redirect=true [NC]
RewriteRule ^(.*)$ - [co=dm_show_classic:true:.example.com:7200:/]
# check no 'dm_show_classic' cookie is set
RewriteCond %{HTTP_COOKIE} !dm_show_classic
# check if no_redirect was sent in the url
RewriteCond %{QUERY_STRING} !no_redirect=true [NC]
# check if the user agent matches supported mobile devices
RewriteCond %{HTTP_USER_AGENT} ((.*iPhone.*)|(.*iPod.*)|(.*BlackBerry.*)|(.*Android.*)|(.*webOS.*)|(.*Windows\ CE.*)|(.*IEMobile.*)|(.*Opera\ Mini.*)|(.*Opera\ Mobi.*)|(.*HTC.*)|(.*LG-.*)|(.*LGE.*)|(.*SAMSUNG.*)|(.*Samsung.*)|(.*Symbian.*)|(.*Nokia.*)|(.*PlayStation.*)|(.*PLAYSTATION.*)|(.*Nintendo\ DSi.*)|(.*TMO-US_LEO.*)|(.*SEC-SGH.*)|(.*BB10.*))
# check if the request isn't for a static file
RewriteCond %{REQUEST_FILENAME} !\.(jpg|gif|png|css|js|txt|ico|pdf|bmp|tif|mp3|wav|wma|asf|mp4|flv|mpg|avi|csv|doc|docx|xls|xlsx|ppt|pptx|zip|rar|tar|gz|dmg|iso)$ [NC]
#### If empty query string then no need to include it ##############
RewriteCond %{QUERY_STRING} ^$
# extract the current page url including the query string
RewriteCond http://%{HTTP_HOST}%{REQUEST_URI} ^(.*)$
# redirect the request to mobile domain and pass the page url as a parameter
RewriteRule ^(.*)$ http://m.example.com?url=%1 [R=301,L]