7
votes

I have an .htaccess file which removes the .php extension from files, converting for example so.com/question.php to so.com/question, and also redirecting the index file in the folder, e.g. so.com/answer/index.php redirects to so.com/answer/ exactly as described in this answer

I have just set up my site locally on IIS7 and need to recreate the same behaviour in a web.config but don't know where to start with converting/rewriting the .htaccess file.

1

1 Answers

31
votes

I have found that IIS7 and above can import Apache .htaccess rules using the URL Rewrite module.

  1. Install the URL Rewrite module via the Microsoft Web Platform Installer
  2. Start IIS Manager and on the left, in the Connections pane, select your required site (e.g. Default Web Site)
  3. In the centre (Features View) double click URL Rewrite.
  4. In the right panel click Import Rules... then paste your rules from the .htaccess file into the Rewrite rules box
  5. Click apply in the right column.

In the specific question above the following .htaccess redirect rules

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

generate the following web.config file.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}.php" matchType="IsFile" ignoreCase="false" />
                    </conditions>
                    <action type="Rewrite" url="{R:1}.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>