web.config有问题,将数字id重写为query_string

时间:2016-02-15 20:08:17

标签: iis web-config rewrite

我想在web.config中使用重写规则来翻译以下网址:

mypage to mypage.php
mydirectory/mypage to mydirectory/mypage.php
mydir2/mydir1/mypage to mydir2/mydir1/mypage.php
mypage/12345 to mypage.php?id=12345
mydirectory/mypage/12345 to mydirectory/mypage.php?id=12345
mydir2/mydir1/mypage/12345 to mydir2/mydir1/mypage.php?id=12345

作为Apache中的.htaccess文件,我只需使用

执行此操作
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^(.*)\/([0-9]+)$ $1.php?id=$2&%1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^(.*)$ $1.php?%1 [L]

我尝试使用web.config在IIS中重现此行为。这是我到目前为止所做的:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.webServer>
<rewrite>
  <rules>
    <rule name="hide .php extension without losing ?id=" stopProcessing="true">
      <match url="^(.*)/([0-9]+)$" ignoreCase="true" />
      <conditions>
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_FILENAME}.php" matchType="IsFile" />
      </conditions>
      <action type="Rewrite" url="{R:0}.php?id={R:2}" />
    </rule>
    <rule name="hide .php extension" stopProcessing="true">
      <match url="^(.*)$" ignoreCase="true" />
      <conditions>
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_FILENAME}.php" matchType="IsFile" />
      </conditions>
      <action type="Rewrite" url="{R:0}.php" />
    </rule>
  </rules>
</rewrite>
</system.webServer>
</configuration>

但是当我进入浏览器并输入http://localhost/mydirectory/mypage/12345时,我找不到404页面。我在404页面上看到请求网址为http://localhost:80/mydirectory/mypage/12345,物理路径为C:\inetpub\wwwroot\mydirectory\mypage\12345

我做错了什么?

1 个答案:

答案 0 :(得分:0)

等等,我明白了。我用

替换了节点name="hide .php extension without losing ?id="
<rule name="hide .php extension without losing ?id=" stopProcessing="true">
  <match url="^(.*)/([0-9]+)$" ignoreCase="true" />
  <conditions>
      <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
      <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Rewrite" url="{R:1}.php?id={R:2}" />
</rule>