Monday, January 21, 2013

500 Internal Server Error / hide .php extension using .htaccess


In my first php project I was required to hide .php extension from the URL. For example if the URL is 'http://localhost/Test/request.jsp' it should display 'http://localhost/Test/request' in browser. I found many links which were showing how to achieve that using .htaccess file however it was not clear where to place that file, under root directory OR under the website directory. I tried both the locations but as soon as i add anything in the file .htaccess it used to give below error.

Error:



500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

I searched many links and finally got the solution, so i am including comprehensive solution here so that if anyone else is facing same issue can use it.

Step 1. I am using WAMPSERVER. Locate the file httpd.conf

Example - C:/wamp/bin/apache/apache2.2.22/conf/httpd.conf

Check for the below line. if it is commented then uncomment it and restart the Services

LoadModule rewrite_module modules/mod_rewrite.so


Step 2. Now create .htaccess file under your website's root directory. You can create it using any text editor, just save its as name '.htaccess' without any extension.

Example - C:/wamp/www/Test/.htaccess (Assuming Test is my website)

Add below code to the file .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Now to test the code let create a index.php and redirect it to request.php. Note - how we are redirecting to request.php, we are just calling 'request' it will automatically rewrite url with '.php' extension.

index.php


<?php
header("Location: request");
exit;
?>


request.php

<h2>This is request.php</h2>


Now hit the below URL, you should see below Output.

http://localhost/Test