HTTP_HOST 和 SERVER_NAME 服务器变量为我提供了 HTTP 请求的主机名(可以是 IP 地址或负载平衡的 DNS,具体取决于请求的发出方式)。我找不到可以给我实际机器名称(即 COMPUTERNAME 环境变量的值)的服务器变量。
我正在尝试在服务器场上设置一些重定向规则,并且有一些基于当前机器名称的规则(例如,内部机器的名称中有 int
)。我不想为每台机器创建单独的规则,而是希望有一些基于当前机器名称的条件逻辑。我似乎找不到获取机器名称的方法。
有什么想法吗?
最佳答案
在 IIS7 中,计算机名称不是内置服务器变量之一。然而,一切并没有丢失,通过使用自定义 UrlRewrite 提供程序的一些工作,您可以在重写规则中显示您的机器名称。
Scott Forsyth 实际上已经构建了类似的东西,并写了一篇描述其使用的博客文章,并提供了源代码和预构建的二进制文件 + 安装程序:
为了在该文章消失的情况下保留此信息,这里大致有以下步骤:
首先在 Visual Studio 中创建一个新的类库项目。您可以在此处找到执行此操作的步骤:
Developing a Custom Rewrite Provider for URL Rewrite Module (IIS.NET)
它们本质上是(以防链接失效):
创建一个类库项目并将其命名为
ServerNameProvider
。 您需要确保项目是 .NET 2.0 或 3.5 项目。 IIS7.5 托管代码支持仍以 2.0 运行时为目标。将默认的
Class1.cs
文件重命名为反射(reflect)提供者用途的名称,例如:ServerName.cs
- 只需确保类名源代码中也反射(reflect)了这一点。添加对:
%ProgramFiles%\Reference Assemblies\Microsoft\IIS\Microsoft.Web.Iis.Rewrite.dll
的引用。在项目属性中创建强名称 key (在签名选项卡上)
添加构建后事件以在您的开发 PC GAC 中安装提供程序程序集(仅用于测试):
CALL "%VS90COMNTOOLS%\vsvars32.bat" > NULL gacutil.exe /if "$(TargetPath)"
请注意,如果使用 Visual Studio 2010,则环境变量
%VS90COMNTOOLS%
应更改为%VS100COMNTOOLS%
。打开
ServerName.cs
文件并确保您的类实现了Microsoft.Web.Iis.Rewrite.IRewriteProvider
接口(interface):using System.Collections.Generic; using Microsoft.Web.Iis.Rewrite; namespace ServerNameVariable { public class ServerName : IRewriteProvider { public void Initialize(IDictionary<string, string> settings, IRewriteContext rewriteContext) { } public string Rewrite(string value) { return System.Environment.MachineName; } } }
构建项目。在您的本地 PC 上,程序集将安装到 GAC 中。
向 IIS 注册提供程序:
appcmd.exe set config -section:system.webServer/rewrite/providers /+"[name='ServerNameVariable',type='ServerNameVariable.ServerName, ServerNameVariable, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5854ff76fb5c07af']" /commit:apphost
Make sure the PublicKeyToken
value in the command line above matches your assembly's public key token. You can extract that value by doing sn.exe -T <assemblyfile.dll>
, for example:
e:\AppDev\..bin\Debug> sn.exe -T ServerNameVariable.dll Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved. Public key token is 5854ff76fb5c07af
The next thing to do is use your new provider in a rewrite rule, for example, here's the example Scott gave which is an outbound rule:
<outboundRules>
<rule name="Set Custom Header" enabled="true">
<match serverVariable="RESPONSE_X_Machine_Name" pattern=".*" />
<action type="Rewrite" value="{ServerNameVariable:}" />
</rule>
</outboundRules>
下面是一个简单的入站规则,如果机器名称是 BOB
,则重定向到 google.com:
<rewrite>
<rules>
<rule name="TestServerVariableProvider"
enabled="true"
stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{ServerNameVariable:}" pattern="BOB" />
</conditions>
<action type="Redirect"
url="http://google.com"
appendQueryString="false"
redirectType="Found" />
</rule>
</rules>
</rewrite>
关于iis - 是否可以在 IIS 7.5 Url 重写模块规则中获取当前机器名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11810007/