Apr 1, 2010
admin

URL Rewriting with PHP and IIS 7

Hello friends !! Few days ago, I faced a URL rewriting problem on windows server. After checking the server configuration, I found that there is an II7 installed. After long research about this, I found that II7 is not support .HTACCESS. If youwant to male your site SEO URL friendly, then you have to use web.config file for URL rewriting instead of .HTACCESS. Now the question is how to make web.config file from .HTACCESS ?

IIS 7 uses a file called Web.config to hold settings for integration with applications. The Web.config file contains information that control module loading, security configuration, session state configuration, and application language and compilation settings. Web.config files can also contain application-specific items such as database connection strings.
Today in this post, I will explain you how to make it ? This post contains most common uses of the .htaccess file by PHP applications, and shows how to use the Web.config file for these same functions in IIS.
Now First Here are the sample files of .HTACCESS and Web.config.

.HTACCESS Sample code

#
# Apache/PHP/Application settings:
#

# Protect files and directories from prying eyes.

Order allow,deny

# Don’t show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Application handle any 404 errors.
ErrorDocument 404 /index.php

# Force simple error message for requests for non-existent favicon.ico.

ErrorDocument 404 “The requested file favicon.ico was not found.

# Set the default handler.
DirectoryIndex index.php

# Override PHP settings. More in sites/default/settings.php
# but the following cannot be changed at runtime.

# PHP 4, Apache 1.

php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0

# PHP 4, Apache 2.

php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0

# PHP 5, Apache 1 and 2.

php_value magic_quotes_gpc 0
php_value register_globals 0
php_value session.auto_start 0
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_value mbstring.encoding_translation 0

# Requires mod_expires to be enabled.

# Enable expirations.
ExpiresActive On

# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600

# Do not cache dynamically generated pages.
ExpiresByType text/html A1

# Various rewrite rules.

RewriteEngine on

# If your site can be accessed both with and without the ‘www.’ prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the ‘www.’ prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the ‘www.’ prefix,
# (http://example.com/… will be redirected to http://www.example.com/…)
# adapt and uncomment the following:
# RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
# RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
#
# To redirect all users to access the site WITHOUT the ‘www.’ prefix,
# (http://www.example.com/… will be redirected to http://example.com/…)
# uncomment and adapt the following:
# RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
# RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

# Modify the RewriteBase if you are using Application in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/application uncomment and
# modify the following line:
# RewriteBase /application
#
# If your site is running in a VirtualDocumentRoot at http://example.com/,
# uncomment the following line:
# RewriteBase /

# Rewrite URLs of the form ‘x’ to the form ‘index.php?q=x’.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

# $Id: .htaccess,v 1.90.2.1 2008/07/08 09:33:14 goba Exp $

Web.config Sample Code

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>

<configSections>
<sectionGroup name=”system.webServer”>
<sectionGroup name=”rewrite”>
<section name=”rewriteMaps” overrideModeDefault=”Allow” />
<section name=”rules” overrideModeDefault=”Allow” />
</sectionGroup>
</sectionGroup>
</configSections>

<system.webServer>
<security>
<!–  This section should be uncommented after
installation to secure the installation. –>
<!–
<requestFiltering>
<denyUrlSequences>
<add sequence=”engine” />
<add sequence=”inc” />
<add sequence=”info” />
<add sequence=”module” />
<add sequence=”profile” />
<add sequence=”po” />
<add sequence=”sh” />
<add sequence=”theme” />
<add sequence=”tpl(\.php” />
<add sequence=”Root” />
<add sequence=”Tag” />
<add sequence=”Template” />
<add sequence=”Repository” />
<add sequence=”code-style” />
</denyUrlSequences>
<fileExtensions>
<add fileExtension=”.sql” allowed=”false” />
<add fileExtension=”.pl” allowed=”false” />
</fileExtensions>
</requestFiltering>
–>
</security>
<directoryBrowse enabled=”true” />
<caching>
<profiles>
<add extension=”.php” policy=”DisableCache” kernelCachePolicy=”DisableCache” />
<add extension=”.html” policy=”CacheForTimePeriod” kernelCachePolicy=”CacheForTimePeriod” duration=”14:00:00:00″ />
</profiles>
</caching>
<rewrite>
<rules>
<rule name=”block favicon” stopProcessing=”true”>
<match url=”favicon\.ico” />
<action type=”CustomResponse” statusCode=”404″ subStatusCode=”1″
statusReason=”The requested file favicon.ico was not found”
statusDescription=”The requested file favicon.ico was not found” />
</rule>
<rule name=”Imported Rule 1″ stopProcessing=”true”>
<match url=”^(.*)$” ignoreCase=”false” />
<conditions>
<add input=”{HTTP_HOST}” pattern=”^example\.com$” />
</conditions>

<action type=”Redirect” redirectType=”Permanent” url=”http://www.example.com/{R:1}” />
</rule>
<rule name=”Imported Rule 2″ stopProcessing=”true”>
<match url=”^(.*)$” ignoreCase=”false” />
<conditions>
<add input=”{REQUEST_FILENAME}” matchType=”IsFile” ignoreCase=”false” negate=”true” />
<add input=”{REQUEST_FILENAME}” matchType=”IsDirectory” ignoreCase=”false” negate=”true” />
<add input=”{URL}” pattern=”^/favicon.ico$” ignoreCase=”false” negate=”true” />
</conditions>
<action type=”Rewrite” url=”index.php?q={R:1}” appendQueryString=”true” />
</rule>
</rules>
</rewrite>
<defaultDocument>
<files>
<remove value=”index.php” />
<add value=”index.php” />
</files>
</defaultDocument>

<!– HTTP Errors section should only be enabled if the “Error Pages”
feature has been delegated as “Read/Write” at the Web Server level.
<httpErrors>
<remove statusCode=”404″ subStatusCode=”-1″ />
<error statusCode=”404″ prefixLanguageFilePath=”" path=”/index.php” responseMode=”ExecuteURL” />
</httpErrors>
–>

</system.webServer>
</configuration>

Default Document

In the .htaccess file for the sample application, the DirectoryIndex directive tells the Web server which file to load if no filename is included with the URL.

# Set the default handler.
DirectoryIndex index.php

For IIS 7, the default document should be set up as high in the Web site hierarchy as the Module Handler. For example, with PHP, the Module Handler is usually set at the Web server level. The default document should be set at that level also, rather than locally within a Web site’s context. The following code within your Web.config file can ensure this:

<defaultDocument>
<files>
<remove value=”index.php” />
<add value=”index.php” />
</files>
</defaultDocument>

Error Page Redirects / Handling using .HTACCESS and Web.config

Some applications handle standard errors within the scope of the application. The ErrorDocument directive in the .htaccess file of the sample application tells the Web server to load the home page for any 404 or “File Not Found” errors.

# Make Application handle any 404 errors.

ErrorDocument 404 /index.php

IIS uses the httpErrors directive for this functionality. However, because the capability to set this at the application level is turned off by default for IIS, this section should be commented out.

<!– HTTP Errors section should only be enabled if the “Error Pages”

feature has been delegated as “Read/Write” at the Web Server level.

<httpErrors>

<remove statusCode=”404″ subStatusCode=”-1″ />

<error statusCode=”404″ prefixLanguageFilePath=”" path=”/index.php” responseMode=”ExecuteURL” />

</httpErrors>

–>

URL Rewriting using .HTACCESS and Web.config

IIS 7 includes the URL Rewrite module. You can use this extension to provide rules for IIS to rewrite incoming URL requests. The most common use of URL Rewriting is to provide shorter, easy-to-remember URLs.

Many PHP applications currently ship with rewrite rules as part of their .htaccess file. These rules tell Apache’s mod_rewrite how and when to rewrite incoming requests. The IIS 7 URL Rewrite module can read these rules and translate them into URL Rewrite rules.

For the sample application codes, the relevant mod_rewrite rules in the .htaccess file are:

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} !=/favicon.ico

RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

The IIS URL Rewriter module can read these rules and translate them. The translated URL Rewriter rules are:

<rewrite>

<rules>

<rule name=”Imported Rule 1″ stopProcessing=”true”>

<match url=”^(.*)$” ignoreCase=”false” />

<conditions>

<add input=”{HTTP_HOST}” pattern=”^example\.com$” />

</conditions>

<action type=”Redirect” redirectType=”Permanent” url=”http://www.example.com/{R:1}” />

</rule>

<rule name=”Imported Rule 2″ stopProcessing=”true”>

<match url=”^(.*)$” ignoreCase=”false” />

<conditions>

<add input=”{REQUEST_FILENAME}” matchType=”IsFile” ignoreCase=”false” negate=”true” />

<add input=”{REQUEST_FILENAME}” matchType=”IsDirectory” ignoreCase=”false” negate=”true” />

<add input=”{URL}” pattern=”^/favicon.ico$” ignoreCase=”false” negate=”true” />

</conditions>

<action type=”Rewrite” url=”index.php?q={R:1}” appendQueryString=”true” />

</rule>

</rules>

</rewrite>

I think this post become very helpful to those peoples who wants to use URL rewriting (SEO friendly URL) in IIS whcih are using PHP.

Feel free to post comment on this post. Thanks You …

  • http://www.programmingfacts.com/ Rakshit

    Nice timir.. Very useful information. Looking forward to see some great articles.

  • http://www.programmingfacts.com Rakshit

    Nice timir.. Very useful information. Looking forward to see some great articles.

  • Pingback: Get Seo Backlink Building Service | Jarhead Musings

  • http://vaiotypep.blogspot.com/ VAIO P’ers

    nice guide!

    uhm, can you make a wildcard version for those rules?

  • http://vaiotypep.blogspot.com/ VAIO P’ers

    nice guide!

    uhm, can you make a wildcard version for those rules?

  • http://www.experl.com/url-rewriting-with-php-and-iis-7/ iss seo

    Nice timir.. Very useful information. Looking forward to see some great articles.

  • Irfaan Ms

    how to use url rewrite for window NT server and php. how to config web.config files? pls tell me..

  • http://www.expertsfromindia.com PHP developer India

    Gone through the post. To check the working of the code and the things you mentioned in the post for that i need to upload the post into my system and then need to execute it.Surely i will get back to you if during execution any problem comes.

  • http://watch-thegreenhornetonline.com/ watch the green hornet online

    Greetings,

    Thanks for sharing this link – but unfortunately it seems to be down? Does anybody here at http://www.phpgenious.com have a mirror or another source?

    Cheers,
    Harry

  • Jkl

    xvcxcvvcxcvxcvcvxccvx

  • Chaitali

    I try these web.config but i got 500 Internal server error

  • Seo Service

    Outstanding ! I always love reading your posts! I really get your way of thinking :)

  • Runysylva

    please convert this for me

    RewriteEngine On

    RewriteRule ([A-Za-z0-9_-]{1,})/([A-Za-z0-9_-]{1,})/([^t]{1}[A-Za-z0-9_-]{0,}).([^s]{1}[A-Za-z0-9_-]{0,})$ ../members/download.php?u=$1/$2/$3.$4

    RewriteRule ([A-Za-z0-9_-]{1,})/([^t]{1}[A-Za-z0-9_-]{0,}).([^s]{1}[A-Za-z0-9_-]{0,})$ ../members/download.php?u=$1/$2.$3

    RemoveHandler .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml
    AddType text/html .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml
    AddHandler server-parsed .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml

    RewriteEngine on
    RewriteBase /

    RewriteRule ^category/([0-9a-zA-Z-]+).html$ index.php?category=$1 [L]
    RewriteRule ^category/([a-zA-Z]+)/([0-9a-z-]+).html$ index.php?category=$2&vd=$1 [L]
    RewriteRule ^catalog/([0-9a-zA-Z-]+).html$ index.php?catalog=$1 [L]
    RewriteRule ^news/([0-9]+)/*$ news/?id=$1 [L]
    RewriteRule ^pages/([0-9a-zA-Z-]+).html$ members/page.php?id=$1 [L]
    RewriteRule ^users/([0-9a-zA-Z-]+).html$ members/user.php?user=$1 [L]

    RewriteRule ^portfolio/([0-9a-zA-Z-]+).html$ members/user_portfolio.php?user=$1 [L]
    RewriteRule ^portfolio/([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+).html$ members/user_portfolio.php?user=$2&vd=$1 [L]

    RewriteRule ^lightbox/([0-9a-zA-Z-]+).html$ members/user_lightbox.php?user=$1 [L]
    RewriteRule ^lightbox/([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+).html$ members/user_lightbox.php?user=$2&vd=$1 [L]

    RewriteRule ^blog/([0-9a-zA-Z-]+).html$ members/user_blog.php?user=$1 [L]
    RewriteRule ^blog/([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+).html$ members/user_blog.php?user=$2&category=$1 [L]
    RewriteRule ^blog/([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+).html$ members/user_blog.php?user=$3&ayear=$1&amonth=$2 [L]
    RewriteRule ^post/([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+).html$ members/user_blog_post.php?user=$1&postid=$2 [L]

    RewriteRule ^testimonials/([0-9a-zA-Z-]+).html$ members/user_testimonials.php?user=$1 [L]
    RewriteRule ^friends/([0-9a-zA-Z-]+).html$ members/user_friends.php?user=$1 [L]

  • Shyamgodara55

    i havent understood

  • Rajenderatoofan56

    1;i++)
    {
    echo “ram”;
    }?>

  • http://itgeared.com/ JM

    Great article, thanks for posting!!!

  • classified

    Hello, Admin
    I faced the problem, when I moved from linx to win server. I have created web.config file, from .htaccess file. then uploaded web.config, my site is down. No error is coming… just browser saying page is not found,

    I have deleted that web.config file, still my website is not working.
    Can you guide me where should be problem?

    Thanks

  • http://www.facebook.com/lemodular.leehome Lemodular Leehome

    Thanks..

  • dan

    Entirely plagiarized from the MS documentation.
    genious => misspelling of the word genius (and nothing else)

Support to grow

If you think my post is helps you then please make donation and do support to grow:

PHP Genious Services

I am a PHP freelancer india, PHP Developer india, PHP programmer india, Wordpress Freelancer india, Wordpress customization services, Wordpress Plugin Developer, Wordpress theme customization, Wordpress plugin customization, Magento Freelancer, Magento Developer india, Magento customization services, Magento theme integration, Opencart Developer india, Zencart Freelancer, Opencart customization, Opencart plugin development, HTML and CSS customization, cakePHP Developer, cakePHP Freelancer india, Ecommerce Developer india

Click Here for

Follow me on Facebook

Categories

Get Adobe Flash player