Redirect all pages to index.php

Viewed 42

I want to redirect all pages to index.php and serve all content from the index.php.

I currently have this in my .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /p/index.php [L,QSA]

When I go to example.com/p/xxxx (not existing php file) it goes to /p/index.php exactly as I would like it.

However, if I go to example.com/p/home it serves the /p/home.php file and I want it to go to /p/index.php.

The .htaccess file is in the /p/ folder.

How can I fix this?

1 Answers

You need to disable MultiViews (part of mod_negotiation). If MultiViews is enabled and /p/home.php exists (when you request /p/home) then that file will be served. MultiViews essentially enables extensionless URLs, but conflicts with mod_rewrite as it is processed first.

For example, at the top of your .htaccess file:

Options -MultiViews

Otherwise, your existing mod_rewrite directives are OK.


update:

The .htaccess file is in the /p/ folder.

Your directives could be simplified/optimised a bit...

RewriteRule ^index\.php - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

The relative substitution string is relative to the directory that contains the .htaccess file, so you don't need to explicitly include the /p directory in the substitution. The QSA flag is not required, since you are not appending a query string in the substitution.

The regex . is more optimal than ^.*$ since you don't need to match everything, you just need to be successful if there is something. When the URL-path is empty then the DirectoryIndex (mod_dir) will serve index.php.

The first rule is simply an optimisation that prevents rewritten requests from undergoing the filesystem check (which is relatively expensive).

Related