Bth
Bth

Reputation: 443

Adding www to urls with url rewrite

I've found this code to add the www to urls without it using url rewrite.

<rewrite>
    <rules>
        <clear />
        <rule name="WWW Rewrite" enabled="true">
            <match url="(.*)" />
            <conditions>
                <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$" />
            </conditions>
            <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>

But it seems to not work of the url has a '-' in it, such as scotts-cleaners.com.

That returns www.www.scotts-cleaners.com.

Any ideas?

Upvotes: 3

Views: 590

Answers (2)

maddrag0n
maddrag0n

Reputation: 459

pattern="^www\.([.a-zA-Z0-9-]+)$"

apparently hyphens don't need escaping in regex ^^

Upvotes: 0

cmbuckley
cmbuckley

Reputation: 42458

Simply add - to the pattern:

<add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9-]+)$" />

Since hyphen and alphanumeric constitute the only allowed characters in a domain name, your pattern should now work for all URLs.

Upvotes: 1

Related Questions