Redirect to mobile default page by UrlRewrite modu

2019-08-27 21:08发布

问题:

Suppose there are two designed pages, one for desktop named mobile.html and the other one is desktop.html, by below UrlRewrite I am able to redirect user to mobile.html

<rewrite>
      <rules>
            <rule name="MobileRedirect" stopProcessing="true">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_USER_AGENT}" pattern="midp|mobile|phone|android|iphone|ipad" />
                </conditions>
                <action type="Redirect" url="/mobile.html" />
            </rule>
      </rules>
</rewrite>

but it trapped in Too Many Request

yourSite redirected you too many times.

it is clear that is because of that rule, it will redirected to mobile.html with no problem but by getting mobile.html that action occurred again, it will dropped in loop redirection. also by adding <add input="{url}" negate="true" pattern="mobile.html"/> it is not working.

回答1:

You can try the following. Add another condition that excludes the mobile.html url.

<rule name="MobileRedirect" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{HTTP_USER_AGENT}" pattern="midp|mobile|phone|android|iphone|ipad" />
    <add input="{PATH_INFO}" pattern="^/mobile.html$" negate="true"/>
  </conditions>
  <action type="Redirect" url="/mobile.html" />
</rule> 


回答2:

If I understand your problem correctly, you want mobile users who land on desktop.html to be redirected to mobile.html and desktop users who land on mobile.html to be redirected to desktop.html. That would require 2 rules as follow:

<rewrite>
      <rules>
            <rule name="MobileRedirect" stopProcessing="true">
                <match url="desktop.html" />
                <conditions>
                    <add input="{HTTP_USER_AGENT}" pattern="midp|mobile|phone|android|iphone|ipad" />
                </conditions>
                <action type="Redirect" url="/mobile.html" />
            </rule>
            <rule name="DesktopRedirect" stopProcessing="true">
                <match url="mobile.html" />
                <conditions>
                    <add input="{HTTP_USER_AGENT}" pattern="midp|mobile|phone|android|iphone|ipad" negate="true" />
                </conditions>
                <action type="Redirect" url="/desktop.html" />
            </rule>
      </rules>
</rewrite>

Note that this 2 rules rely on user agent which are never 100% reliable (since they can be changed).