![](/img/trans.png)
[英]how to set asp.net web.config rewrite http to https and www to non-www
[英]“non-www to www” and “https” rewrite rule in web.config but not localhost ASP.NET MVC
我的ASP.NET MVC 5项目的web.config
中具有以下重写规则:
<rule name="Redirect example.com to www.example.com and enforce https" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAny">
<add input="{HTTP_HOST}" pattern="^[^www]" />
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
该规则将非www重定向到www,将http重定向到https(因此类似http://example.com/hey
将重定向到https://www.example.com/hey
)并且可以正常工作。 但是,它也可以在localhost
,而且我似乎无法解决该问题-我尝试了包含|
否定规则和正则表达式|
但似乎无法找到正确的组合。 我是否以错误的方式处理此问题?
在conditions
块中,可以使用属性negate="true"
。 如果设置了此属性且条件匹配,则不应用重写规则。
IIS.net的negate
属性的描述:
可以通过使用元素的negate属性来否定模式。 使用此属性时,仅当当前URL与指定的模式不匹配时,才执行规则操作。
由于您使用的是MatchAny
,因此添加附加属性将不匹配,因为无论如何至少要满足其中一个条件。 我建议将2个特定的重写规则与logicalGrouping="MatchAll"
,其中每个规则仅负责一种情况:
<rule name="enforce https" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTPS}" pattern="off" />
<add input="{HTTP_HOST}" matchType="Pattern"
pattern="^localhost(:\d+)?$" negate="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
appendQueryString="true" redirectType="Permanent" />
</rule>
<rule name="Redirect example.com to www.example.com"
enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_HOST}" pattern="^[^www]" />
<add input="{HTTP_HOST}" matchType="Pattern"
pattern="^localhost(:\d+)?$" negate="true" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:1}"
appendQueryString="true" redirectType="Permanent" />
</rule>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.