简体   繁体   中英

Redirect non-www to www with IIS URL Rewrite generically without hardcoding domain or TLCD

I am building an ASP.NET CMS-driven web application which will serve multiple websites under different domain names. Some of these will use www sub-domain, others will use custom sub-domains. There will be a variety of top-level country domains.

I'm looking for a generic IIS URL Rewrite rule that will redirect any URL which doesn't specify a sub-domain to its www equivalent.

When I say generic it means the rule cannot hard-code either domain name or top-level country domain. So the rule must redirect http://anything.anywhere/any-path to http://www.anything.anywhere/any-path but leave http://sub.anything.anywhere/any-path .

The closest I've found is this which still hard-codes TLCD. Without much knowledge of the syntax of URL Rewrite I'm not sure how to handle any TLCD.

Thanks in advance.

Update:

Inspired by comment, I've had a go with regex, but haven't yet found a method that doesn't require me to hard-code a list of all possible TLCDs. I suspect this is the best I'll get. Can anyone refine or confirm this as the answer?

^([a-z]+[.](com|co.uk|de|fr|etc)+)*

I just did the exact same thing using a rewrite rule with two conditions, one to get the Scheme and one to determine if the www is missing. The scheme is necessary as the redirect has to be absolute, but if your not catering for HTTPS that could be hard-coded. Just bear in mind I've not had time to test the HTTPS part yet, but pretty sure it will work ok.

<?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Root Redirect" stopProcessing="true">
                        <match url=".*" negate="false" />
                        <action type="Redirect" url="{C:1}://www.{HTTP_HOST}/{R:0}" />
                        <conditions trackAllCaptures="true">
                            <add input="{CACHE_URL}" pattern="^(.*)://" />
                            <add input="{HTTP_HOST}" pattern="^(?!www\.).*" />
                        </conditions>
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM