We are excited to announce that the IIS.NET Forums are moving to the new Microsoft Q&A experience. Learn more >

URL rewrite for Mobile/Cell phone devices [Answered]RSS

22 replies

Last post Dec 14, 2012 05:21 PM by Rovastar

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    URL rewrite for Mobile/Cell phone devices

    Jul 22, 2010 06:10 AM|Rovastar|LINK

    I recently had a need for writing a rewrite rule for mobile (cell) phone devices.

    It is getting more common now for large sites to cater for the growing amounts of the mobile/cell traffic in different ways. In the organisation I am with at the moment they had a completely separate site for all the mobile users where they could download apps etc.

    So I went about creating a rule for redirecting all mobile content from our main sites.

    Most of our traffic to our busy sites is UK centric so there might be slight variations in other region and traffic patterns I don't know how well this will translate into other regions but I think this is a very good start. It capture 99.9+% of mobile traffic for me.

    There will always be exceptions and the standards for mobile browsers is next to non existence but these rules seem to catch nearly all the mobile traffic.

    The way I approached this was to look at the User Agent string in the request. This tell me about the browser the mobiles are using....well sometimes.  Google user agent strings of mobile and you will see a myriad of options also some of this data is old and not a true representation of newer mobile devices.

    So I first collected all the useragents I could. I wrote some Log Parser rules and went through GBs worth of logs. I found the following.

    Most of the Mobile devices User Agent strings contained the following unique terms that didn't appear for desktop browsers.

    MIDP  (http://en.wikipedia.org/wiki/Mobile_Information_Device_Profile)

    or

    mobile 

    or 

    phone

    (sometimes the case can vary when these terms are used)

    So the rule was created around these terms. Most mobile manufacturers seemed to follow these terms  (I would be interested in seeing any widely used mobiles that don't use these terms)

    So that was a great basis for a rewrite rule. However it wasn't as easy as that some mobile/cell operators like Vodafone decide sometimes to route there traffic through a proxy. When routed through this proxy it changes the useragent string to a generic desktop browser looking one. Obviously a complete pain luckily they send an additional header with original user agent under the user defined X field  X-Device-User-Agent so we check that too for the same terms.

     

    Also the growing popularity of opera mini/mobile as a browser has again a more generic user agent that it is indistinguishable from a desktop browser (we really don't want valid desktop traffic going to the mobile only content site). Luckily they also send another custom X header along with the request with the original user agent the phone uses this is X-OperaMini-Phone-UA. We also check this too.

    Sorry for the long explanation but I thought it was needed for explaining about mobile devices and how the networks can fit together and the pitfall you get.

    Anyway here is rule just drop it into your web.config under <configuration><system.webServer> :

    <rule name="Mobile Rewrite" patternSyntax="ECMAScript" stopProcessing="true">
    
        <match url=".*" ignoreCase="true" negate="false" />
    
        <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
    
            <add input="{HTTP_USER_AGENT}" pattern="midp|mobile|phone" />
    
            <add input="{HTTP_X-Device-User-Agent}" pattern="midp|mobile|phone" />
    
            <add input="{HTTP_X-OperaMini-Phone-UA}" pattern="midp|mobile|phone" />
    
        </conditions>
    
        <action type="Redirect" url="http://mysite.mobi" appendQueryString="false" redirectType="Found" />
    
    </rule>

    Where the Redirect in this case is going to http://mysite.mobi so you will have to change this to the site/directory you require.

    I hope you find this useful and if you have any questions/suggestions about this or just find it useful then just drop them here in this thread.

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    Jul 27, 2010 04:32 AM|Leo Tang - MSFT|LINK

    Hi,

    Thanks for share, Rovastar!

    Please mark the replies as answers if they help or unmark if not.
    Feedback to us


  • Re: URL rewrite for Mobile/Cell phone devices

    Aug 11, 2011 05:48 AM|TomTom1234|LINK

    thanks for that excellent sample!!! one question though, what if i wanted the users to be able to view the full version of a page despite the redirect? so on my mobile version, i want to include a link "view full version" without getting them redirected back again ...
  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Aug 11, 2011 07:42 PM|Rovastar|LINK

     I hadn't thought of that scenario when I created this rule. I'll give it some thought.....not sure how to "override" a redirect though

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    Sep 27, 2011 07:16 PM|mcastells|LINK

    I think you can just add another condition with negate="true", for example

    <add input="{QUERY_STRING}" pattern="desktop=1" negate="true" />

    then add ?desktop=1 onto the link.

  • Re: URL rewrite for Mobile/Cell phone devices

    Nov 16, 2011 02:10 PM|mikeberlin|LINK

    mcastells

    I think you can just add another condition with negate="true", for example

    <add input="{QUERY_STRING}" pattern="desktop=1" negate="true" />

    then add ?desktop=1 onto the link.

    This works for the initial load of the full web site, but what happens when a user clicks on a link within the full site. It would revert back to the mobile site correct? Since the querystring wouldn't be in the link clicked.

    I'm struggling with this right now. I can get the device detection working and the redirection with no problems. But I'm not sure how to persist the querystring once the user clicks a link in the full web site.

    Any help would be appreciated!

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Nov 17, 2011 05:20 PM|Rovastar|LINK

    After some thought I am not sure it can be done effectively.

    Maybe coding it could be done (something based on your session) but not ideal.

    However you could have an additional subdomain for the main normal site which you could redirect to like www1.mysite.com and this never autorediects based on the mobile useragent. Once on that domain for the main site as long as nothing is hardcoded for paths back to www.mysite.com (it shouldn't be in a modern site but no accounting for devs ;) ) you will stay on it.

    So you have a condition to ignore the rule if www1. or whatever in the domain.

    And in your hostheader/ Bindings have:

    www.mysite.com

    mysite.com'

    and additionally

    www1.mysite.com

    Not perfect but the best I can think of. just have to get the business to prescribe to having www1.mysite.com (or whatever) for peopel going to the site.

    If you really want desktop/non-mobile traffic never going to www1.mysite.com you could have a similar url redirect  (based on the above rule) it to the regular www.mysite.com

    Hope that makes sense and is a solution to some and something I think I will try if needed.

     

     

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    Nov 17, 2011 05:38 PM|mikeberlin|LINK

    Rovastar

    After some thought I am not sure it can be done effectively.

    Maybe coding it could be done (something based on your session) but not ideal.

    However you could have an additional subdomain for the main normal site which you could redirect to like www1.mysite.com and this never autorediects based on the mobile useragent. Once on that domain for the main site as long as nothing is hardcoded for paths back to www.mysite.com (it shouldn't be in a modern site but no accounting for devs ;) ) you will stay on it.

    So you have a condition to ignore the rule if www1. or whatever in the domain.

    And in your hostheader/ Bindings have:

    www.mysite.com

    mysite.com'

    and additionally

    www1.mysite.com

    Not perfect but the best I can think of. just have to get the business to prescribe to having www1.mysite.com (or whatever) for peopel going to the site.

    If you really want desktop/non-mobile traffic never going to www1.mysite.com you could have a similar url redirect  (based on the above rule) it to the regular www.mysite.com

    Hope that makes sense and is a solution to some and something I think I will try if needed.

     

     

    Hello and thank you for your reply!

    Our setup has www.mysite.com and m.mysite.com and the IIS rules (mobile device redirection to m.mysite.com) are setup on the www site. To resolve the need for a "View Full Site Link" on the mobile site I setup an outbound rule that detects if the querystring matches fullsite=1. If it does then it rewrites all the href properties within anchor tags to include the fullsite=1 querystring. Here's the rule that I'm using:

    <outboundRules>
    <rule name="Persist fullsite qs var" preCondition="IsHTML">
    <match filterByTags="A" pattern="^(.+?)(\?(.+))*$" />
    <action type="Rewrite" value="{R:1}?fullsite=1&{R:3}" />
    <conditions>
    <add input="{QUERY_STRING}" pattern="fullsite=1" />
    </conditions>
    </rule>
    <preConditions>
    <preCondition name="IsHTML">
    <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
    </preCondition>
    </preConditions>
    </outboundRules>

    So if a user clicks the View Full Site link (which points to www.mysite.com?fullsite=1) it goes to the inbound rules (which I added a to bypass the mobile redirection if the querystring contains fullsite=1), which renders the site with the fullsite=1 in the url and then the above outbound rule kicks in (rewriting the anchor tags with the fullsite=1 in the querystring). If there is no querystring in the href property will contain a trailing & but that doesn't effect anything. If you find a way to remove that let me know.

    I hope this helps anyone that has a similar problem.

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Nov 17, 2011 06:21 PM|Rovastar|LINK

    Nice solution. I like the outbound rule idea. We have a few ways of doing it now. 

    What about another rule to rewrite anything with /& (and nothing else) to remove the &

    so www.mysite.com/? rewrites to www.mysite.com

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    Nov 18, 2011 10:58 AM|mikeberlin|LINK

    That sounds like it would work. Any idea what regex could be used for that? I'm anything but proficient with regex. They're are two scenarios the regex would need to consider:

    http://m.mysite.com/default.aspx?fullsite=1&
    Rule should remove the tailing &

    http://m.mysite.com/default.aspx?fullsite=1&myqsvar=1234
    Rule should not remove the & since it's not trailing.

    So just removing the last instance of the & wouldn't work. Any help would be appreciated!

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Nov 18, 2011 07:30 PM|Rovastar|LINK

     This regex works ([^.]*)&$

    <rule name="remove last ampersand" stopProcessing="true">
                        <match url="([^.]*)&amp;$" />
                        <action type="Redirect" url="{R:1}" />
    </rule>  

    Removes  ([^.]*) is everything before and

    &$ (converts to  &amp;$ in the web.config displays correctly in the GUI) matches the & to the last character

    The $ operator matches the very last character. Here is a good regex site about the $ operator:

    http://www.regular-expressions.info/anchors.html

     

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    Jan 11, 2012 05:04 PM|OWScott|LINK

    Great thread and discussion.

    I haven't setup a test, so I'm trying to understand, but with the querystring solution wouldn't that fail on any server side redirects within code?  For example a login page.  The server wouldn't be aware of the fullsite=1 so the URL would drop the fullsite=1.  Is that correct?

    The other option that could work is to have the "View Full Site" link point to a page that writes a cookie and then redirects to the equivalent www page.  The redirect-to-mobile rule can have a condition where the cookie doesn't exist.

    I haven't setup an end to end example, but it seems to me like it would also work and would be trustworthy throughout the site.

    Scott Forsyth
    Microsoft MVP - IIS/ASP.NET
    Dynamicweb North America
    www.dynamicwebusa.com
  • Re: URL rewrite for Mobile/Cell phone devices

    Jan 12, 2012 08:06 PM|mikeberlin|LINK

    Yes, I believe you're correct in saying that any server-side redirects would invalidate the query string solution (unless the redirects read the query string and persist it on). Thankfully that's not the case with the site that I'm working with.

    The only question I have about the cookie solution is if cookies are generally enabled by default, or even supported, on mobile devices. I thought about setting a cookie before going down the route before I learned about the URL rewrite plugin.

    My thought was if we take the uncertainty of knowing if the mobile device supports (or has enabled) cookies then it would be a solid solution. Thus the query string solution.

  • Re: URL rewrite for Mobile/Cell phone devices

    Jan 13, 2012 09:54 AM|OWScott|LINK

    You raise a good point Mike. It looks like it's not accepted as a safe assumption to use cookies on mobile phones: http://www.w3.org/TR/mobile-bp/#d0e1925. If your site doesn't have any server-side redirects then your solution works great.

    And I've just thought of another method that should be very safe and easy to do. Use a 3rd domain name.

    For example, www.domain.com should redirect all mobile phones to m.domain.com. Then if someone clicks on "View Full Site" send them to mweb.domain.com. The mweb.domain.com can point to the same site as www.domain.com but you now have a new condition to check against. Unless something in the site is hard coded to use the full domain name, client-side and server-side redirects should maintain the URL.

    Also, add a robots.txt files to ask the search engines to not index m.domain.com and mweb.domain.com.

    Scott Forsyth
    Microsoft MVP - IIS/ASP.NET
    Dynamicweb North America
    www.dynamicwebusa.com
  • Re: URL rewrite for Mobile/Cell phone devices

    Apr 30, 2012 09:45 AM|anh1e|LINK

    Great article.

    Found the list of user agent string for mobile browsers http://www.useragentstring.com/pages/Mobile%20Browserlist/

    Based on that list, if we search with pattern="midp|mobile|phone", are we going to miss a lot of mobile browsers ?

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Apr 30, 2012 10:04 AM|Rovastar|LINK

    Although this was initially written nearly 2 years ago I still think that it catches most mobile browsers.

    Which ones did you think it would not catch? There may be a few in the change mobile market but most are there that have any significant traffic

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    May 07, 2012 09:51 PM|halcoberry|LINK

    I recently wrote a post up with screenshots on using the URL Rewriter to redirect specific browsers.

     here it is if you are interested

    http://halcoberry.blogspot.com.au/

    *edit cause i cant spell :p

    browser redirect specific

  • Re: URL rewrite for Mobile/Cell phone devices

    Nov 01, 2012 04:51 PM|Dil|LINK

    We are using IIS URL Rewrite module to redirect all request from a mobile browser to m.mymobilesite.com by checking HTTP_USER_AGENT. This works fine and now we need to implement a "View Full Site" link which will allow the user to see the main site. Trying to achieve this by adding a "nomobile" cookie when user clicks on "View Full Site" link which will be validated and negated by the rule. For some reason my rule doesn't seems to work. Please help.

    <rewrite>
    <rules>
        <rule name="MobileRedirect" patternSyntax="ECMAScript" stopProcessing="true">   
            <match url=".*" ignoreCase="true" />
            <conditions logicalGrouping="MatchAll">
                <add input="{HTTP_COOKIE}" pattern="nomobile" ignoreCase="true" negate="true" />
                <add input="{HTTP_USER_AGENT}" pattern="android|blackberry|googlebot-mobile|iemobile|iphone|ipod|opera mobile|palmos|webos" />
            </conditions>   
            <action type="Redirect" url="http://m.mymobilesite.com" appendQueryString="false" redirectType="Found" />
        </rule>
    </rules>

    </rewrite> 

     

    IIS7 urlrewrite

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Nov 07, 2012 07:43 AM|Rovastar|LINK

    The easiest way is to through it the failed request tracing.

    http://www.iis.net/learn/extensions/url-rewrite-module/using-failed-request-tracing-to-trace-rewrite-rules

     

    Troubleshoot IIS in style
    https://www.leansentry.com/
  • Re: URL rewrite for Mobile/Cell phone devices

    Nov 08, 2012 05:26 PM|Dil|LINK

    Thank you.
  • Re: URL rewrite for Mobile/Cell phone devices

    Dec 13, 2012 09:38 AM|md.ather|LINK

    Dear Rova,

    Thank you for the information. Currently my client has IIS 7 and Above. Our website is runnng on dot.net.

    From the rule I am unable to make out as where I have to write the rule. Can you please help on this. As I am bit new to this knowledge domain.

    Ather

  • Re: URL rewrite for Mobile/Cell phone devices

    Dec 13, 2012 09:38 AM|md.ather|LINK

    Dear Rova,

    Thank you for the information. Currently my client has IIS 7 and Above. Our website is runnng on dot.net.

    From the rule I am unable to make out as where I have to write the rule. Can you please help on this. As I am bit new to this knowledge domain.

    Ather

  • Rovastar Rovastar

    5495 Posts

    MVP

    Moderator

    Re: URL rewrite for Mobile/Cell phone devices

    Dec 14, 2012 05:21 PM|Rovastar|LINK

    just drop in into your web.config under 

    <configuration>

      <system.webServer>

    I have update the original article to include this.

    Troubleshoot IIS in style
    https://www.leansentry.com/