Question

I'm using mod rewrite to access my PHP files in the root directory of my website indirectly. Currently, I have something like this,

RewriteRule ^(blog|about|page3|etc)$ /$1.php [L]

But what I would like to use is

RewriteRule ^(.*)$ /$1.php [L]

So that I wouldn't have to update my .htaccess file whenever I wanna add a new page to my website. The problem with this however is that it affects my subdirectories too. Which makes CSS, javascript, images unaccessable because it redirects to "/dir/example.png.php".

So what is the best solution here?

Was it helpful?

Solution

Try this rule:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule .* $0.php [L]

OTHER TIPS

Edit the .htaccess to this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1.php [L]

After starting the rewrite engine, it will first check to see if the requested file is an actual file on the system, or if it is actually a directory. If it is neither of those, it will execute the rule, which in this case is to try and find the file by appending .php and serving that up.

Subdirectories, images, CSS and the like will be fine because they will step out of the rewriting once they are found.

I'd do it with filters to ignore sub-directories. That way you only have to change it if you add a sub folder. You'll need to add a line like Sosh's if you have images or other files in the folder

The following would ignore "images" and "js" sub folders and redirect everything else

RewriteRule   ^images*   -  [L]
RewriteRule   ^js*       -  [L]
RewriteRule   ^(.*)$     /$1.php   [L]

Something like this (note the !):

RewriteRule !\.(js|ico|gif|jpg|png|css|zip|gz|html|xml)$ index.php
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top