Search code examples
php.htaccessurlphp-extension

How to remove .php extension the pro way


I have created my first Php solution but have trouble removing the .php extension from the URL. It works in the root but not in sub-folders?

Eg www.domain.com/index.php reached from www.domain.com/index (or www.domain.com/)

Then it gets tricky.

For example. www.domain.com/en/europe/bikes/racer-bike.php will not differ from www.domain.com/en/bikes/racer-bike without ending up on www.domain.com/en/bikes/ and on index.php

My .htaccess file looks like this:

Options -MultiViews
RewriteEngine on
RewriteBase /

# Remove .php-extension from url
RewriteCond %{REQUEST_URI} ^/(.*).php$
RewriteRule ^(.*)$ %1 [L,QSA]

# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]

# SSL
RewriteCond %{HTTP_HOST} ^domain.com$
RewriteRule ^(.*)$ http://www.domain.com$1 [R=301]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/?(.*)$ https://%{SERVER_NAME}/$1 [L,R=301,QSA]

Solution

  • I Try it and it works:

    My dirs structure

    /
    index.php
    /sub
        file.php
    

    And my htaccess like this:

    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^/([^\/]*)$
    RewriteRule ^([^\/]*)$ $1.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ([A-Za-z]+)/(.*)$ [NC]
    RewriteCond %{DOCUMENT_ROOT}/%1 -d
    RewriteRule ^([A-Za-z]+)/(.*)$ $1/$2.php [NC,L,QSA]
    

    Try it