Htaccess - rewrite files that have a directory with the same name

I have a website with several PHP files and directories with the same name:

/projects.php /projects /projects/something.php 

I managed to make a http://example.com/projects rewrite to http://example.com/projects.php with the following rules (using the answer here ):

 RewriteEngine On # Disable automatic directory detection DirectorySlash Off # Hide extension RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php 

This works, however, when I explicitly put the cosine of the directory in the URL, it accesses the folder. Right now:

 http://example.com/projects --> http://example.com/projects.php [file] http://example.com/projects/ --> http://example.com/projects/ [folder] 

I know why this is done ( projects/.php not a file). My attempt to fix this was to check if it was a folder, and instead of replacing the slash and access to it.

New .htaccess:

 RewriteEngine On # Disable automatic directory detection DirectorySlash Off # Hide extension RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php # Folder fix RewriteCond %{REQUEST_FILENAME} -d RewriteRule (.*)/$ $1.php 

This works as intended, however it gets completely confused on the client side, as the client still has a folder in the url, so when it tries to get relative paths, it fails.

Now I thought about doing a redirect with the flag [R=301] , but as far as I know, %{REQUEST_FILENAME} refers to the server, so redirecting to it will not work.

If someone could point me in the right direction, that would be very appreciated!

+6
source share
1 answer

Try putting this line at the top:

 Options -MultiViews 

More on this

The hiding rule .php should be:

 RewriteEngine On # Disable automatic directory detection DirectorySlash Off RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^(.+?)/?$ /$1.php [L] 
+6
source

Source: https://habr.com/ru/post/957529/


All Articles