ASP.net url rewrite force lowercase

2019-07-23 12:05发布

问题:

I have:

<!-- Force lowercase URLS -->
<rewrite url="~/(.*[A-Z]+.*)$" to="~/handlers/permredirect.ashx?URL=${lower($1)}" />

Perm redirect simply 301 redirects to the new URL.

This rule is meant to redirect any URL with an uppercase char to the lower case one.

This however creates a redirect loop, any ideas why? The only rules running so far are:

<rewriter>

    <!-- Remove Trailing Slash for all URLS-->
    <rewrite url="~/(.*)/($|\?(.*))" to="~/handlers/permredirect.ashx?URL=${lower($1)}$2" />

    <!-- Force lowercase-->
    <rewrite url="~/(.*[A-Z]+.*)$" to="~/handlers/permredirect.ashx?URL=${lower($1)}" />

    <rewrite url="~/construct2($|\?(.*))" to="~/construct2.aspx" processing="stop" />
</rewriter>

回答1:

You can either modify the regular expression to exclude .ashx files (which might get extremely complicated) or create a new rule before this rule, that will catch URLs pointing to ashx files and redirect them to a lowercase version of the string.

Something like this might work (not tested):

<rewrite url="~/(?=(.*\.ashx.*))(.*[A-Z]+.*)" to="~/${lower($1)}" />

It uses a lookahead rule to check if ".ashx" is part of the url and if the URL is uppercase. If yes, it redirects to the lowercase version of the same url.