Using WordPress ‘iis7_add_rewrite_rule()’ PHP function

The iis7_add_rewrite_rule() WordPress PHP function adds a WordPress rewrite rule to the IIS 7+ configuration file.

Usage

iis7_add_rewrite_rule( $filename, $rewrite_rule );

Parameters

  • $filename (string) – The file path to the configuration file.
  • $rewrite_rule (string) – The XML fragment with the URL Rewrite rule.

More information

See WordPress Developer Resources: iis7_add_rewrite_rule()

Examples

Adding a Basic Rewrite Rule

In this example, we’ll add a simple rewrite rule to redirect all requests to the index.php file.

$filename = 'web.config';
$rewrite_rule = '
<rule name="WordPress" 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="index.php" />
</rule>';

iis7_add_rewrite_rule($filename, $rewrite_rule);

Redirecting Non-WWW to WWW

Add a rewrite rule to redirect all non-www requests to www.

$filename = 'web.config';
$rewrite_rule = '
<rule name="Redirect to www" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^example\.com$" />
  </conditions>
  <action type="Redirect" url="http://www.example.com/{R:1}" redirectType="Permanent" />
</rule>';

iis7_add_rewrite_rule($filename, $rewrite_rule);

Force HTTPS

Add a rewrite rule to force HTTPS for all requests.

$filename = 'web.config';
$rewrite_rule = '
<rule name="Force HTTPS" enabled="true">
  <match url="(.*)" ignoreCase="false" />
  <conditions>
    <add input="{HTTPS}" pattern="off" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>';

iis7_add_rewrite_rule($filename, $rewrite_rule);

Redirect from One Path to Another

Add a rewrite rule to redirect requests from /old-path/ to /new-path/.

$filename = 'web.config';
$rewrite_rule = '
<rule name="Redirect old path to new path" stopProcessing="true">
  <match url="^old-path(/.*)?$" />
  <action type="Redirect" url="/new-path{R:1}" redirectType="Permanent" />
</rule>';

iis7_add_rewrite_rule($filename, $rewrite_rule);

Remove File Extension

Add a rewrite rule to remove the .html file extension from URLs.

$filename = 'web.config';
$rewrite_rule = '
<rule name="Remove .html extension" enabled="true">
  <match url="^(.*)\.html$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  </conditions>
  <action type="Rewrite" url="{R:1}" />
</rule>';

iis7_add_rewrite_rule($filename, $rewrite_rule);