当存在具有相同名称的目录时,htaccess重写all到index.php失败

Hello I'm trying to accomplish the following:

1) Remove trailing slashes

2) Redirect every request to root index.php even if there is a directory with the same name as in the url. Let's assume I have a folder with name 'users', I dont want 'http://local.dev/users' to redirect me to the folder but instead handle it via php like the rest requests.

3)I want to be able to access any type of image , js, css and some other specific file types even if they are inside a directory.

What I have so far is this:

RewriteEngine on
RewriteBase /
RewriteRule ^(.*)/$ $1 [R=301,L]
RewriteCond %{REQUEST_URI} !^.*\.(png|jpg|jpeg|bmp|gif|css|js|json|csv)$ [NC]
RewriteRule ^(.*)$ index.php?path=$1 [NC,L,QSA]

and php for testing cases:

<!DOCTYPE html>
<html>
    <head>
        <title>+dev</title>
    </head>
    <body>
        <?php
            echo $_SERVER['REQUEST_URI'] . '<br>';
            print_r($_GET);
            echo '<br>';
            include 'test/test.php';
        ?>
        <img src="/image.jpg">
        <img src="/test/image2.jpg">
    </body>
</html>

However I noticed the following issue:

Keep in mind that I have a folder named test in my root directory next to htaccess and index.php

http://local.dev/test/image.jpg = works

http://local.dev/somestring = works

http://local.dev/someImage.jpg = works

http://local.dev/test/ = fails

http://local.dev/test = fails

browser url output in 2 last cases:

http://local.dev/test?path=test&path=test&path=test&path=test&path=test&path=test&path=test&path=test&path=test&path=test

Yeap redirect loop, but I can't figure out why since I'm not that familiar with mod_rewrite. What I would like, is the last 2 failed requests to be treated as plain request regardless if there is a folder with the same name. Although I want the files inside that folder to be accessible if their extension is on the "allow list".

Change to:

RewriteEngine on
RewriteBase /
RewriteRule ^(.*)/$ $1 [R=301,L]
RewriteRule !\.(png|jpg|jpeg|bmp|gif|css|js|json|csv)$ index.php [NC,L]

The reason this is happening is because of mod_dir and the DirectorySlash directive. Essentially, if it sees a URI without a trailing slash, and it maps to an existing directory, then it'll redirect the request so that it has the trailing slash. Since mod_dir and mod_rewrite are both in different places in URL-file processing pipeline, both mod_dir and mod_rewrite get applied to the same URL.

So you need to turn DirectorySlash off (can put this anywhere in your htaccess file):

DirectorySlash Off