Matt Matt - 18 days ago 5
Apache Configuration Question

htaccess remove .php extension and rewrite to www

I'm trying to accomplish 2 things in htaccess that is located in my root directory and should affect all web pages throughout my website. I'm using Apache 2.4.

1) Rewrite non-www to www (this part is currently working)

2) Remove .php extension from URL

For #2 I found two threads about this but when trying to implement it with code from #1 it never seems to work.

Remove .php extension with .htaccess

How to hide the .html extension with Apache mod_rewrite

Here is my code, the first part works fine but the second part doesn't seem to do anything for me as ".php" still shows up on all URL's.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]


I also looked at this thread and tried the following, still not working.

5 .htaccess Rewrites: Force HTTPS, Remove index.php, Remove .php, Force www, Force Trailing Slash

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.(?!js|css)([^.]*)$ $1\.php

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


Any help would be appreciated. Thanks in advance.

UPDATED

Here is the folder structure and where the PHP code exists. Most php files are in the root folder but there are two additional folders that contain PHP code.

/
index.php
file1.php
file2.php
file3.php
file4.php
folder1/file5.php
folder1/file6.php
folder2/file7.php
folder2/file8.php

Answer

You can use:

RewriteEngine On
Options -MultiViews

# Redirect to http(s)://www
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# remove php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]

# Rewrite to php
RewriteCond %{DOCUMENT_ROOT}/$1.php -f 
RewriteRule ^(.+)/?$ /$1.php [L]