Unexpected request handling with substrings of exi

2019-09-14 03:38发布

问题:

Let http://test.server/ be my current web server for testing purposes then I have a folder in there called Homepage which holds the code for the homepage (duh.). In the Homepage folder there are a some folders (like Templates) which have .htaccess files with deny from all. In Homepage I do have a quite long .htaccess as well with the following contents:

<IfModule mod_speling.c>
    CheckSpelling off
    CheckCaseOnly off
</IfModule>

Options -MultiViews

RewriteEngine On
RewriteBase /Homepage
ErrorDocument 403 /Homepage/403
ErrorDocument 404 /Homepage/404

# Block direct access to files and directories in these directories
RewriteCond %{REQUEST_URI} !\.(?:jpe?g|gif|bmp|png|tiff|css|js|ico)$ [NC]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(Forbidden) - [NC,F]

# Deny access to configuration files
<Files  ~ "\.ini">
    Order allow,deny
    Deny from all
</Files>

# Remove index.php
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*?)index\.php$ /$1 [L,R=301,NC,NE]

# Redirect Trailing Slashes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w-]+)/([\w-]+)/?$ index.php?page=$1&id=$2 [L,QSA,NC]
RewriteRule ^([\w-]+)?/?$ index.php?page=$1 [L,NC,QSA]

So when i try to access http://test.server/Homepage/Templates/ this invokes a 403 error and the specified ErrorDocument described by /Homepage/403 is properly shown (and parsed by my backend) while still being on http://test.server/Homepage/Templates/.

However, when I try to access a Url that is a substring of the protected folder like http://test.server/Homepage/Template/, http://test.server/Homepage/Temp/ etc. the server redirects (!) to http://test.server/Template/ or http://test.server/Temp/ and shows a generic 404 document that was not setup since I have no .htaccess in the root folder. I was expecting the ErrorDocument for 404 to be shown like 403 does correctly while still being at http://test.server/Homepage/Temp/ for example. This means this isn't even sent to my handler in my index.php but directly handled by Apache which seems to be trying to find some fallback rules in the root folder.

What's the mistake I made in my .htaccess?

回答1:

Problem is due to this # Redirect Trailing Slashes rule.

You can replace that rule with:

# Redirect Trailing Slashes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.*)/$
RewriteRule ^ %1 [L,R=301,NE]

Clear your browser cache before testing this change.