首先到iis官网上下载IIS URL Rewrite 2.0并安装
http://www.iis.net/downloads/microsoft/url-rewrite
安装完成后重启一下机器,就会在IIS管理器中看到URL重写的功能区
注:IIS URL Rewrite 2.0仅在IIS 7.0及以上版本才能正常工作
双击URL重写图标,进入URL重写页面,点击右侧添加规则
这里我参考官网的例子,通过正则表达式重写^article.php/([0-9]+)/([_0-9a-z-]+)到页面article.aspx?id={R:1}&title={R:2}
如重写http://localhost/article.php/234/some-title页面将234和some-title分别作为参数传给article.aspx文件,即重写到http://localhost/article.aspx?id=234&title=some-title配置后的规则截图如下:
注:可通过测试模式来验证正则表达式书写是否正确
配置完成后访问http://localhost/article.php/234/some-title页面的效果如下:
如果您打开web根目录(wwwroot/)会发现下面多了一个文件web.config文件,它类似我们Apache服务器中的.htaccess文件,本例中对应的web.config文件内容为:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to article.aspx">
<match url="^article.php/([0-9]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="article.aspx?id={R:1}&title={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
所以您也可以直接在该文件中完成规则的修改,另article.aspx的代码如下:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>URL Rewrite Module Test</title>
</head>
<body>
<h1>URL Rewrite Module Test Page</h1>
<table>
<tr>
<th>Server Variable</th>
<th>Value</th>
</tr>
<tr>
<td>Original URL: </td>
<td><%= Request.ServerVariables["HTTP_X_ORIGINAL_URL"] %></td>
</tr>
<tr>
<td>Final URL: </td>
<td><%= Request.ServerVariables["SCRIPT_NAME"] + "?" + Request.ServerVariables["QUERY_STRING"] %></td>
</tr>
</table>
</body>
</html>
后记:
在实际操作中,Alan需要将NewsDetail.php?newsid=976跳转到new/detail.aspx?ID=976,那么问题来了,通过上面的方法并不能正常跳转,而是报了404。这主要是因为请求链接中包含了问号,这里即做去问号做转义也是没有用的,本处需要用到的是{QUERY_STRING},有多少个字段就在conditions里添加多个人add:
<rule name="My Rewrite">
<match url="^NewsDetail.php" />
<conditions logicalGrouping="MatchAll">
<add input="{QUERY_STRING}" pattern="newsid=([0-9]{1,4})" />
</conditions>
<action type="Rewrite" url="new/detail.aspx?ID={C:1}" />
</rule>







