0

I've been trying to make adding the '.php' file extension optional in URLs. So if I had an URL like 'www.example.com/page.php', 'www.example.com/page' would also work. And I managed to do it (this article and this StackOverflow question is where I tried to take solutions from).

Here for example is the solution I found on the article page:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

But there was a problem, because I had an URL that was like 'www.example.com/articles/index.php'. While 'www.example.com/articles/index' worked, 'www.example.com/articles' would no longer lead to the index page, even after I tried to add a DirectoryIndex (with values like 'index.php' or even just 'index').

Is there some other way to hide a file extension like '.php', while still making the index file work as intended?

Marked as Duplicate
  • 1,117
  • 4
  • 17
  • 39

2 Answers2

0

You can use:

Options -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+)/?$ $1.php [L]

Who tests if the php file exists

Croises
  • 18,570
  • 4
  • 30
  • 47
0

You can do this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php [NE,L]

Only one file test instead of three, so more efficient than the other answer.

  • But it does not work if a folder has the same name as a php file. Or if the user added a / final, which is not unusual for a directory. – Croises Jun 24 '17 at 18:21
  • Why would the user want to have a folder named the same as a PHP file? They would just use index.php in that folder. And if that edge case is needed, an exception can be added (but it has not been asked for in the question, and again, it's unlikely). There is no need to test for every request, which is poor for performance. –  Jun 24 '17 at 18:22