Score:0

Remove both index.php and file extension on other php pages using .htaccess

cn flag

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?

Score:0
cn flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.