Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove .php extension (explicitly written) for friendly URL [closed]

htaccess to remove the .php extension of my site's files.

RewriteEngine on
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L,QSA]

Now, if I go to my site

www.mysite.com/home

works fine, it redirects to home.php but the URL is still friendly.

But if I write this URL:

www.mysite.com/home.php

The home.php is served, and the URL is not friendly.

How can I avoid this behavior? I want that if the user writes www.mysite.com/home.php, the URL displayed in the URL bar be www.mysite.com/home

like image 531
miquel Avatar asked Nov 30 '22 06:11

miquel


1 Answers

Code

RewriteEngine On
RewriteBase /

# remove enter code here.php; use THE_REQUEST to prevent infinite loops
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]


# remove index
RewriteRule (.*)/index$ $1/ [R=301]

# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]

# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]
like image 87
Bhavana Avatar answered Dec 04 '22 02:12

Bhavana