Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove .php extensions with web.config on IIS7

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.

like image 581
ajcw Avatar asked Sep 15 '12 21:09

ajcw


1 Answers

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>
like image 126
ajcw Avatar answered Oct 06 '22 12:10

ajcw