Setting up URL Rewrite rule for a specific domain

好久不见. 提交于 2020-01-01 04:43:14

问题


For local dev testing, I need to catch all requests to www.somedomain.com/XXX (where X is the path), and send them on to localhost/somevdir/XXX.

I've added this to my HOSTS file (c:\windows\system32\drivers\etc):

127.0.0.1   www.mydomain.com

Then, in IIS8 (Windows 8), I've added a binding to my "Default Web Site" for the host www.mydomain.com. This works, I can now browse www.mydomain.com/test.html and see a test html page. My virtual dir is inside the Default web site. I then add a URL Rewrite URL to the web site for the last bit:

<rewrite>
    <rules>
        <rule name="mydomain.com" stopProcessing="true">
            <match url="^www.mydomain.com/(.*)" />
            <action type="Rewrite" url="localhost/MyVDir/{R:1}" logRewrittenUrl="true" />
        </rule>
    </rules>
</rewrite>

But - that doesn't work. I get a 404 so it looks the the match never happens. I've tried redirect and rewrite, and I've tried without the ^ in the regex and a few other regex tweaks. Can someone explain what I've done wrong?


回答1:


I think the following should work:

<rule name="mydomain.com" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^(mydomain\.com|www\.mydomain\.com)$" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Redirect" url="http://localhost/MyVDir/{R:1}" redirectType="Temporary" />
</rule>

The match on any URL makes sure the conditions are checked, and the HTTP_HOST server variable seems the most reliable way of checking the requested hostname. You could remove the REQUEST_FILENAME input condition, but it works as quite a nice sanity check to make sure static files are always served.




回答2:


The following is better for catching both www. and non-www. versions of the domain so that you don't have to write the domain twice, which could possibly cause errors with being twice as likely to write a typo. (The parenthesis with the ? character means optional in regex terms.)

<rule name="mydomain.com" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^(www.)?mydomain\.com$" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Redirect" url="http://localhost/MyVDir/{R:1}" redirectType="Temporary" />
</rule>


来源:https://stackoverflow.com/questions/17063005/setting-up-url-rewrite-rule-for-a-specific-domain

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