.htaccess 如何维护一个文件夹和文件具有相同名称但同时隐藏该文件扩展名的网站?

n3ipq98p  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(119)

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

ipakzgxi

ipakzgxi1#

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.

相关问题