5

I am looking for a way to hide the file extension via .htaccess and deny direct access. Let's consider the following:

http://www.xyz.zyx/index.php 

gets converted to

http://www.xyz.zyx/index OR http://www.xyz.zyx/

All good till now. What I want to do next is block or redirect when the user tries a direct access. Example, if the user types in the URL bar the following (extension), block or redirect:

http://www.xyz.zyx/index.php

I checked the other answers from other questions, but non seemed to be exactly it.

Thanks in advance for helping a newbie like me.

Andrei Durduc
  • 280
  • 3
  • 8
  • possible duplicate of [Redirect *.php to clean URL](http://stackoverflow.com/q/2267488/), [hide extension .php in url mod_rewrite](http://stackoverflow.com/q/6241408/) – outis Apr 29 '12 at 05:11

1 Answers1

7

Although one may question the usefulness of such a thing, it's feasible, so here's how to do it in a .htaccess using mod_rewrite:

RewriteEngine On

# Sets your index script
RewriteRule ^$ index.php [L]

# Condition prevents redirect loops (when script is not found)
RewriteCond %{ENV:REDIRECT_STATUS} !^$
RewriteCond %{REQUEST_FILENAME} !-f

# Stop here if the file is not found after a redirect
RewriteRule ^(.*)$ notfound.php [L]

# Condition prevents redirect loops (when script is found)
RewriteCond %{ENV:REDIRECT_STATUS} ^$

# Forbid access directly to PHP files
RewriteRule ^.*?\.php$ forbidden [F,L]

# Make sure the filename does not actually exist (images, etc.)
RewriteCond %{REQUEST_FILENAME} !-f

# Append the .php extension to the URI
RewriteRule ^(.*)$ $1.php [L] 
netcoder
  • 66,435
  • 19
  • 125
  • 142