IIS: Rewrite URL with regex but keep query strings

ⅰ亾dé卋堺 提交于 2021-01-29 05:01:21

问题


I'm have the following link

https://example.com/myapp/green?&lang=en&instance=some%20instance

I need to rewrite it to the following link

https://example.com/myapp?color=green&lang=en&instance=some%20instance

The color in the link can be any color but it needs to be rewritten like in the 2nd link so that the trailing slash is replaced with a ? followed by the word color= and the ? at the end of the color word needs to be removed.

/myapp/green? becomes /myapp?color=green,

/myapp/blue? becomes /myapp?color=blue

and so forth, all while keeping the rest of the query string &lang=en&instance=some%20instance intact

I've tried regexing my way out of this but I usually catch everything or unintentionally omit the rest of the query string.

Any ideas on what's the best approach?

EDIT: noticed that IIS, when applying to application level (not website level), the input URL path is after '/myapp/' and I need that trailing slash removed. Does this mean I'll have to apply it to the website level?


回答1:


You could use below url rewrite rule(add this rule at site level):

<rule name="color query" enabled="true" stopProcessing="true">
                <match url="myapp/(.*)/$" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{QUERY_STRING}" pattern="lang=(.*)&amp;instance=(.*)" />
                </conditions>
                <action type="Redirect" url="http://www.sample1.com/myapp?color={R:1}&amp;lang={C:1}&amp;instance={C:2}" appendQueryString="false" />
            </rule>

Note: you could not remove the myapp/ from URL it will be added automatically in URL.



来源:https://stackoverflow.com/questions/60440822/iis-rewrite-url-with-regex-but-keep-query-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!