Regex URL match on anything but www

2019-09-01 06:45发布

问题:

I'm using IIS7 and the URL Rewrite module.

I would like to use regex to match any subdomain apart from www.

So...

frog.domain.co.uk = Match
m.domain.co.uk = Match
anything.domain.co.uk = Match
www.domain.co.uk = No match

This way I can redirect any subdomain that someone types in back to www.

回答1:

you can use 301 in .htaccess for this.



回答2:

This will match what you want:

^(?!=www\.).*

Which is a negative lookahead for www.. Not sure if you need the trailing .*



回答3:

Use this rule -- it will redirect to www.exmaple.com domain if domain is different:

<system.webServer>
      <rewrite>
          <rules>
              <rule name="Force www" stopProcessing="true">
                  <match url="(.*)$" />
                  <conditions>
                      <add input="{HTTP_HOST}" pattern="^www\.example\.com" negate="true" />
                  </conditions>
                  <action type="Redirect" url="http://www.example.com/{R:1}" />
              </rule>
          </rules>
      </rewrite>
  </system.webServer>

You can optimize it a bit if you do not want to type domain name twice (example.com) -- but that is very minor thing and depending on your circumstances/configuration it is can be undesired.