htaccess regex-使用url /最后斜杠之后的最后目录的字符串进行FilesMatch

问题描述

我这里有一个代码,用于重写URL,拒绝具有扩展名的文件名并允许特定文件

RewriteEngine On
# XAMPP /Brian
# Trailing Slash
RewriteCond %{REQUEST_URI} !/Brian/$
RewriteCond %{REQUEST_URI} !\.[^/]*$
RewriteRule !/$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
# XAMPP /Brian
#Exclude from redirect
RewriteCond %{REQUEST_URI} !^/Brian/index.PHP$
RewriteCond %{REQUEST_URI} !^/Brian/pass.txt$
RewriteCond %{REQUEST_URI} !^/Brian/dist/.*\.(css|js)$

RewriteRule .* index.PHP

<FilesMatch "[^/]*(?!.*\/)\..*$">
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</FilesMatch>

<FilesMatch "\.(PHP|css|js|txt)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

示例:

http://localhost:8080/Brian/pass -> http://localhost:8080/Brian/pass/ # CORRECT,slash added
http://localhost:8080/Brian/pass.txt -> http://localhost:8080/Brian/pass.txt # CORRECT,no slash added,no error 403
http://localhost:8080/Brian/pass.txts -> http://localhost:8080/Brian/pass.txts # CORRECT,error 403
http://localhost:8080/Brian/pass.txt/pass2-> http://localhost:8080/Brian/pass.txt/pass2/ # CORRECT,no error 403
http://localhost:8080/Brian/pass.txt/pass2.txt -> http://localhost:8080/Brian/pass.txt/pass2.txt # CORRECT,no error 403

我的问题是这个。

http://localhost:8080/Brian/pass.txts/pass2.txt -> http://localhost:8080/Brian/pass.txts/pass2.txt # NOT CORRECT,error 403

我注意到 FilesMatch 仅读取第一个斜杠之前的字符串,该斜杠是pass.txts而不是pass2.txt

如何使它读取最后一个斜杠之后的最后一个字符串?需要帮忙。谢谢!

已更新:

RewriteEngine On
# XAMPP /Brian
# Trailing Slash
RewriteCond %{REQUEST_URI} !/Brian/$
RewriteCond %{REQUEST_URI} !\.[^/]*$
RewriteRule !/$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
# XAMPP /Brian
#Exclude from redirect
RewriteCond %{REQUEST_URI} !^/Brian/index.PHP$
RewriteCond %{REQUEST_URI} !^/Brian/pass.txt$
RewriteCond %{REQUEST_URI} !^/Brian/dist/.*\.(css|js)$

RewriteRule .* index.PHP

RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$
RewriteRule ^[^/.]+\.[^/.]+$ - [F]

RewriteRule !\.(PHP|css|js|txt)$ - [NC,F]

解决方法

<FilesMatch "[^/]*(?!.*\/)\..*$">
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</FilesMatch>

使用mod_rewrite规则将此块替换为:

RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$
RewriteRule ^[^/.]+\.[^/.]+$ - [F]

然后:

<FilesMatch "\.(php|css|js|txt)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

使用mod_rewrite规则将此块替换为:

RewriteRule !\.(php|css|js|txt)$ - [NC,F]

这将与.txt中的REQUEST_URI相匹配,而不是从REQUEST_FILENAME中获取。 F用于将Forbidden403返回给客户。


您的完整.htaccess文件:

DirectoryIndex inddex.php
RewriteEngine On
# XAMPP /Brian
# Trailing Slash
RewriteCond %{REQUEST_URI} !/Brian/$
RewriteCond %{REQUEST_URI} !\.[^/]*$
RewriteRule !/$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REMOTE_ADDR} !^(127\.0\.0\.1|::1)$
RewriteRule ^[^/.]+\.[^/.]+$ - [F]

RewriteRule !\.(php|css|js|txt)$ - [NC,F]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/Brian/(index\.php|pass\.txt|/dist/.*\.(css|js))$ [NC]
RewriteRule . index.php [L]