Rewriting URLs in IIS7

2019-07-07 02:35发布

问题:

I have been following http://learn.iis.net/page.aspx/806/seo-rule-templates/, which is a nearly perfect guide to creating SEO friendly URLs in IIS7.

I have one problem though:

If I create a rule to rewrite www.domain.com/contact/ I get in web.config:

<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
  <match url="^([^/]+)/?$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Rewrite" url="?p={R:1}" />
</rule>

But then i can't do www.domain.com/contact/send/.

If I create a rule to rewrite www.domain.com/contact/send/ I get in web.config:

<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
  <match url="^([^/]+)/([^/]+)/?$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Rewrite" url="?p={R:1}&amp;a={R:2}" />
</rule>

But then I can't do www.domain.com/contact/

Both of the rules do so that I can't see any scripts, css og images from my /scripts/, /css/ and /images/ folders.

How do I make a rule to match both AND to NOT match the 3 folders mentioned above?

回答1:

Your rule could be something like this (I have expanded and commented it for an easier understanding and eventual editing):

^
    (
        (?!css|scripts|images)  # The directories you don't want to match
        [^/]+                   # The matched directory
    )
    (
        /
        (
            ([^/]+)             # Optional part
            /?                  # Optional trailing slash
        )?
    )?
$

Which translates into the following:

<match url="^((?!css|scripts|images)[^/]+)(/(([^/]+)/?)?)?$" />

The rewrite url should then be updated to: ?p={R:1}&amp;a={R:4} because of the changes in the number of captures of the new regular expression.