Apache 2.4 – Removing index.php and File Extensions Using .htaccess

.htaccessapache-2.4

I would like to remove the need to include index.php in my links. Instead of

example.com/about/index.php

I would like it to be

example.com/about/

Secondly, I would also like other non-index pages to be navigable without the .php file extension in the url. Instead of

example.com/about/who_we_are.php

I would like it to be

example.com/about/who_we_are

I am having no luck getting both to work simultaneously. Here is what I have in my .htaccess file:

Options -Indexes
DirectoryIndex index.php index.htm index.html
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Currently, it is removing .php from non-index pages but all of the directory index pages are redirecting to the homepage.

What am I doing wrong?

Best Answer

Shortly after posting this question I found a solution to this problem.

# remove .php; use THE_REQUEST to prevent infinite loops
RewriteCond %{HTTP_HOST} ^www\.example\.com
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]

# remove index
RewriteRule (.*)index$ $1 [R=301]

# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]

# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

I hope this helps anyone else searching for a solution to this problem.

Related Topic