.htaccess replace .php with / for every PHP file .htaccess replace .php with / for every PHP file apache apache

.htaccess replace .php with / for every PHP file


Try this:

RewriteEngine onRewriteBase /RewriteCond %{REQUEST_FILENAME} !-d # not a dirRewriteCond %{REQUEST_FILENAME} !-f # not a fileRewriteCond %{DOCUMENT_ROOT}/$1.php -f # but php existsRewriteRule ^([^/]+)/([^/]+)?$ $1.php?p=$2 [L]

However http://domain.com/file without the trailing / returns a page not found error.

That's because your rule does not match unless there's a / at the end.

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

You can make it optional with ? as

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

Note, that / does not need a \ before it. It works with or without it.

Also I need to know how to auto redirect http://domain.com/file.php to http://domain.com/file/

# Rewrite original .php request to new URLsRewriteCond %{THE_REQUEST} \ /([^.]+)\.php [NC]RewriteRule ^ /%1/ [R,L]# Resolve the new URLs to .php filesRewriteRule ^(.*?)/?$ $1.php [L]

If you get this working first, we can see what we can do about the query parameters later.


Your final htaccess could look like

# Rewrite original .php request to new URLsRewriteCond %{THE_REQUEST} \ /([^.]+)\.php [NC]RewriteRule ^ /%1/ [R,L]# Force a trailing / if not a fileRewriteCond %{REQUEST_URI} !\..{3,4}$RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]# Redirect to php if not an existing dirRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)/$ $1.php [L]


You'll probably want something like this:

RewriteEngine onRewriteBase /# redirect with trailing parameterRewriteRule ^([\w]+).php?p=([\w]+)$ $1/$2/  [QSA,R=301]# redirect bare php filesRewriteRule ^([\w]+).php$ $1/  [QSA,R=301]# make sure it's not a request to an existing fileRewriteCond %{REQUEST_FILENAME} !-f# make sure we have a trailing slashRewriteRule ^(.+[^/])$ $1/  [QSA,R=301]# internally point to the right fileRewriteRule ^([^/]+)/([^/]*)/?$ $1.php?p=$2 [QSA,L]

The [R=301] appendixes redirect the browser to the new URL with a 301, moved permanently status header. That way the browser will know where to find the right url in the future, without asking the server.

Also, sometimes an .htaccess checker is useful: http://htaccess.madewithlove.be/ Do note, the tool doesn't work with %{REQUEST_FILENAME}.