2

I want to remove the .php and .html extensions of my website pages in the browser. I found this code online to add in the .htaccess file:

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

However, if a have a php file named "home.php" and at the same time a directory named "home" this doesn't work anymore. I think I might have to add something like

Options All -Indexes -MultiViews

but I like this it does not work either. So how can I achieve this?

jcaron
  • 17,302
  • 6
  • 32
  • 46
Philipp
  • 404
  • 1
  • 5
  • 17
  • 2
    So if you call `yourdomain.com/home` what is supposed to be requested - `home.php` script or `home` directory? What exactly you want to achieve? What if you have `home.php` as directory name or `home` as script name with no extension? You must think off all scenarios. – Wh1T3h4Ck5 Mar 10 '18 at 10:15
  • So calling `domain.com/home` should display `home.php`. Then I want to have a folder called `home` with other php files in it, e.g. `about.php`, such that I can call `about.php` via `domain.com/home/about`. Can I achieve this using the `.htaccess` file? – Philipp Mar 10 '18 at 10:25
  • 1
    Remove the `!-d` rule. – Niet the Dark Absol Mar 10 '18 at 11:38
  • 2
    That looks like a pretty good beginning of tons of problems... – Nico Haase Mar 10 '18 at 11:39
  • Why not just rename `home.php` into `home/index.php`, and be done with it. – CBroe Mar 10 '18 at 12:46

2 Answers2

5

You could be able to give a priority to file when it request comes without / with same name with directory as well as removing both php & html and determine which one to check first like this :

DirectorySlash Off
RewriteEngine on 
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.(php|html)[\s?/] [NC]
RewriteRule ^ /%1%2 [R=302,L,NE]
RewriteCond %{REQUEST_FILENAME}   !-f 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*) /$1.php [L]
RewriteCond %{REQUEST_FILENAME}   !-f 
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*) /$1.html [L]
RewriteCond %{REQUEST_FILENAME}   !-f 
RewriteCond %{REQUEST_URI} !\/$
RewriteRule ^(.*) %{REQUEST_URI}/ [L,R=302]

So , by the code above , extensions will be removed then will check first if there is php file match this , then html and finally if there is a directory .

So , the request for /home only will check first a php that named home if it is exist ok , then directory home but the request /home/about will go directly to about inside home directory.

Clear browser cache then test it , if it is Ok , change 302 to 301 to get permanent redirection

Mohammed Elhag
  • 4,272
  • 1
  • 10
  • 18
0

You can try with this simple code in your .htaccess

RewriteEngine On
RewriteRule ^([^\.]+?)/?$ $1.php [NC,L]

Update: As @Niet mentioned I missed condition so add this line before rule.

RewriteCond %{REQUEST_FILENAME}\.php -f
Wh1T3h4Ck5
  • 8,399
  • 9
  • 59
  • 79