Phillip Dews
Phillip Dews

Reputation: 338

How to remove index.php using htaccess

I am currently building a PHP-based portfolio site without any frameworks whatsoever. I have created an index.php file in the root and a lot of folders namely /about, /contact, /portfolio and the like. Within each of those, I have a separate index.php file

I created a .htaccess file and in it, I have this code...

Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

For some reason when I visit my site at example.com/index.php or example.com/about/index.php the .htaccess file is not working and removing it.

Any ideas why?

Upvotes: 1

Views: 1228

Answers (2)

MrWhite
MrWhite

Reputation: 45948

RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

If the intention with these directives is to remove index.php from the requested URL then you are using the wrong rules! This rule would route a request for /something to index.php/something (passing the requested URL-path as path-info to index.php) providing /something does not map to a file or directory.

You have presumably structured your URLs so they map to filesystem directories from which the DirectoryIndex is served, so the above directives would seem to be entirely redundant. (?)


To remove index.php from the end of any URL

To remove index.php (the DirectoryIndex) from any URL you would need to do something like the following instead:

RewriteRule ^(.+/)?index\.php$ /$1 [R=301,L]

Test first with a 302 (temporary) redirect to avoid potential caching issues.

To clarify...

  • you must not be linking internally to /index.php or /about/index.php. The above directive is only for when a user or external site erroneously requests the index.php file directly.

  • And include trailing slashes on your internal links. eg. you should be internally linking to /about/ and /contact/ etc. (not /about or /contact), otherwise mod_dir will implicitly issue a 301 redirect to append the trailing slash.

Upvotes: 1

Phillip Dews
Phillip Dews

Reputation: 338

It took a while and thanks for the suggestions by Mr White this is my solution..

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L,QSA]

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

Works perfectly now. Thank you for everyone who took the time out to help me on this.

Upvotes: 0

Related Questions