Here is a quick guide on how to

1.  rewrite index.php to root

2. redirect .php to no extension (non .php)

3.  rewrite non .php to .php

using a .htaccess file

To do this the order of the rules in the htaccess file is very important and it should be in this order.

So, your code will look like this: 

- redirect index.php URL requests to example.com/ 
- redirect .php URL requests to correct extensionless URL (this redirect will never affect index.php because the rule above has already fixed that problem)
- redirect non-www to www (canonical 301 redirect)
- rewrite extensionless URL requests to the correct .php file.

So here is how we do it in the .htaccess file

First we turn on the redirect engine

#Turn on Redirect engine 
RewriteEngine on 
RewriteBase / 

Then we redirect index.php or index.html to the root of the domain

# redirect index.php URL requests to example.com/ 
RewriteRule ^index\.(php|html?)$ http://www.example.com/ [R=301,L] 

Then we redirect the .php file request to the non php

# redirect to .php-less link if requested directly 
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+ 
RewriteRule ^(.+)\.php $1 [R=301,L] 

Then we rewrite the the non .php file requests to the correct .php file

# rewrite extensionless URL requests to the correct .php file 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

The final .htaccess file should look like this

#Turn on Redirect engine 
RewriteEngine on
RewriteBase /

# redirect index.php URL requests to example.com/
RewriteRule ^index\.(php|html?)$ http://www.example.php/ [R=301,L]

# redirect to .php-less link if requested directly
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+
RewriteRule ^(.+)\.php $1 [R=301,L]

# rewrite extensionless URL requests to the correct .php file
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php
How to: CentOS, Virtualmin – htaccess rewrite index.php, redirect .php to no extension, rewrite non .php to .php
Tagged on:                                                                     

Leave a Reply

Your email address will not be published. Required fields are marked *

2 thoughts on “How to: CentOS, Virtualmin – htaccess rewrite index.php, redirect .php to no extension, rewrite non .php to .php

  • We stumbled over here different website and thought I may as well check
    things out. I like what I see so nnow i am following you.Look forward to
    looking over your wweb page for a econd time.