htaccess php文件,然后文件夹

问题描述 投票:0回答:1

我在我的

.htaccess
文件中使用以上内容

# BEGIN - Allow Sucuri Services
<IfModule mod_rewrite.c>
    RewriteRule ^sucuri-(.*)\.php$ - [L]
</IfModule>
# END - Allow Sucuri Services

<Files 403.shtml>
order allow,deny
allow from all
</Files>

# Disable MultiViews
Options +FollowSymLinks -MultiViews

RewriteEngine on

# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

# Allow extensionless PHP URLs to work
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+)$ $1.php [L]

# Front-controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ci_index.php?/$1 [L]

我面临的问题是每当我尝试打开文件

https://www.example.com/world-data
它打开文件夹-
https://www.example.com/world-data/
而不是
https://www.example.com/world-data.php

如何防止打开文件夹而不是文件?

php apache .htaccess mod-rewrite
1个回答
0
投票

我面临的问题是每当我尝试打开文件

https://www.example.com/world-data
它打开文件夹-
https://www.example.com/world-data/
而不是
https://www.example.com/world-data.php

通常,在构建无扩展名的 URL 时,您应该尽量避免这种情况,因为它会产生歧义——只有一个可以访问。

发生这种情况是因为 mod_dir 在您请求文件系统目录时“修复”了 URL without 尾部斜杠。它通过在尾部附加斜杠和 301(永久)重定向来实现。这是必要的,以便从该目录(如果有)提供

DirectoryIndex

为了覆盖此行为并防止 mod_dir 附加尾部斜杠(并最终服务于

DirectoryIndex
),您需要在
.htaccess
文件的顶部附近设置以下内容(在
Options
指令之后是一个合乎逻辑的位置把它)。

DirectorySlash Off

但是,您需要确保清除浏览器(和任何中介)缓存,因为早期的 301(永久)重定向(附加尾部斜线)将被浏览器持久缓存。

参考:https://httpd.apache.org/docs/2.4/mod/mod_dir.html#directoryslash

但是(#1),您还需要确保禁用自动生成的目录列表(mod_autoindex),否则即使存在

DirectoryIndex
文档,您也会发现文件结构暴露。因此,相应地修改
Options
指令:

# Disable MultiViews and directory listings
Options +FollowSymLinks -MultiViews -Indexes

但是(#2),如果省略尾部斜杠,这实际上会使所有目录都无法访问。如果您希望请求的目录没有尾部斜杠,那么您需要手动附加尾部斜杠,因为 mod_dir 将不再为您执行此操作。例如,在附加

.php
文件扩展名的规则之后(即在代码中的
# Allow extensionless PHP URLs to work
规则之后)添加以下内容:

# Append the trailing slash to directories (if required)
RewriteCond %{DOCUMENT_ROOT}/$0 -d
RewriteRule .*[^/]$ /$0/ [R=301,L]

在哪里

.*[^/]$
匹配任何不以尾部斜杠结尾的URL路径。如果映射到物理目录的 URL 路径不包含点,则可以进一步优化以从正则表达式中排除点(以避免测试静态资产)。例如。
^[^.]*[^/]$
(不包括字符串开始锚点)。

$0
反向引用包含与
RewriteRule
pattern 匹配的整个 URL 路径。


对不起,我忽略了你对我之前的回答所做的评论。尽管这本身确实值得一个答案,因为它不一定是微不足道的修复。

© www.soinside.com 2019 - 2024. All rights reserved.