Regex to redirect a url using url rewrite

2019-09-17 14:28发布

OK, I'm wondering if someone can lend a hand with a regex I'm trying to write.

Basically, what I want to do is use IIS urlrewrite module to do a redirect to a specific URL if the user accesses a URL on another site. The only catch is I have to also capture a bit of the query string, and move it into the redirect.
so here is the input, the URL that a user may access would look like:

https://of.example.com/sfsv3.aspx?waform=pro&language=en

I want to match that URL (either http or https, case insensitive), and capture from it also one piece of information, the two letter language code. then the url i want to forward the user to looks like:

http://example.com/ca/en/ppf

(where en is replaced by whatever i captured above)

So, I'm working with IIS Rewrite module, and I've gotten my input data and regex in, so far the regex pattern I have is this:

https?://of.example.com/sfsv3.aspx\?waform=pro&(language=(..))

so basically i'm matching the whole string, plus a group and a subgroup for language and it's code. in the IIS test pattern dialog, this is working.

I get the following

{R:1} language=en

{R:2} en

great! so then my IIS rewrite rule should look like this to redirect the user:

<system.webServer>
    <rewrite>
      <rules>
        <rule name="test" stopProcessing="true" enabled="true">
          <match url="https?://of.example.com/sfsv3.aspx\?waform=pro&amp;(language=(..))" ignoreCase="true" />
          <action type="Redirect" url="http://www.example.com/ca/{R:2}/ppf" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

this all seems right to me. however, the redirect is not occurring. it seems to have a problem with the part \? (an escaped question mark to mark the start of the query string). if this is included, then the redirect simply does not happen.

Can you help me figure out how to get it work?

1条回答
戒情不戒烟
2楼-- · 2019-09-17 14:58

for the record, I figured it out. this is a special case of regex, running it inside a web.config as part of a urlrewrite action. in that case, you can't handle the query string with simple regex, you have to put in conditions on the query string. Here's what eventually ended up working:

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="redirect" stopProcessing="true" stopProcessing="true" enabled="true">
                    <match url="sfsv3.aspx\.aspx" ignoreCase="true"/>
                    <conditions>
                        <add input="{QUERY_STRING}" pattern="subject=PROPRCH" />
                        <add input="{QUERY_STRING}" pattern="(..)/subject" />
                    </conditions>
                    <action type="Redirect" url="https://www.example.com/ca/{C:1}/forms/ppf" appendQueryString="false"/>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
查看更多
登录 后发表回答