Search code examples
phpapache.htaccess

htaccess rewrite rule remove subdirectory and .php extension


I need to rewrite the url of my web and make it hide subfolder and the .php extension, like this:

original : http://192.168.100.5/project/controller/report.php?unit=1&year=2021

goal : http://192.168.100.5/project/report?unit=1&year=2021

My current rules which doesnt work

Options -Indexes
RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f

RewriteRule ^(.*)$ controller/$1.php [L]

How to achieve this? thankyou


Solution

  • You will need 2 .htaccess files.

    site root .htaccess:

    RewriteEngine On
    
    # forward everything to controller/ if not a file or directory
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* controller/$0 [L]
    

    controller/.htaccess:

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