Home > Enterprise >  How can I maintain a website where a folder and file have the same name but also hide the extension
How can I maintain a website where a folder and file have the same name but also hide the extension

Time:12-14

I am trying to improve the structure of my urls by using .htaccess. I have a file named foo.php and a folder named /foo. I want to be able to access example.com/foo and show example.com/foo.php. I also want to be able to access example.com/foo/bar and show example.com/foo/bar.php. Lastly I want to reditrect from example.com/foo/ to example.com/foo. Does anyone know how to do this?

This is my code:

RewriteEngine On
DirectorySlash Off

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.] )$ $1.php [NC,L]

I am able to remove the .php extension by I am not able to redirect from the folder to the file. I also tried the solutions below but none of them resulted in the desired behaviour.

htaccess - Rewrite files that have a directory with the same name

.htaccess, rewriting of filename with same name as directory

.htaccess, proper rewriting of directory and file with same name

CodePudding user response:

I found a workaround solution to this problem. In order to remove the extension from file names, I used the following code in my .htaccess file:

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

The above code allows me to go to example.com/foo and show example.com/foo.php. In order to redirect from example.com/foo/ to example.com/foo, I created an index.php file in the /foo directory. I added the following PHP code to the file

<?php 
  $page = str_replace('/index.php', '', $_SERVER['PHP_SELF']);
  header("Location: $page");
?>

This redirects from the directory to the file. Hope this helps.

  • Related