Search code examples
phpapache.htaccesshttp-redirectsef

Remove PHP extension using .htaccess methods (Keeping Link Juice)


I'm trying to remove the .php extension on my URLs to make it Search Engine Friendly using the .htaccess file Redirect 301, to keep the "rank juice" and I as much I've tried almost every example around - It just doesn't seem to work.

Here are some of the methods I've unsuccessfully tried already:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

This is the most common solution given but nothing happens and there is no changes.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1.php [L]

Nothing happens and there is no changes.

RewriteEngine On
# RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
# RewriteRule (.*)\.php$ /$1 [L,R=301]
# RewriteRule (.*)/$ $1.php [L]

I get a Not Found : The requested URL /AMENPTHOME/hostnd/3/9/9/399fc7b78/www/htdocs/web/dive-sites.php was not found on this server.

Amen is my host and the file dive-sites.php in this specific real example is on the root. My goal is to have: www.domain.com/dive-sites and not www.domain.com/dive-sites.php using a Redirect 301 because this url is already ranked for a while. Can someone please help ?

Thank you very much, all help appreciated.


Solution

  • If I didn't missed anything:

    RewriteEngine On
    
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC]
    RewriteRule ^ /%1 [R=301,NE,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L]
    

    Requests to /dive-sites.php will issue a 301 redirect to /dive-sites, appending query-strings if any.

    Requests to /dive-sites will get a 200 response with /dive-sites.php as Content-Location, appending query-strings if any.