.htaccess - 拒绝使用 .htaccess 直接访问文件或目录

标签 .htaccess mod-rewrite apache2

我正在玩 .htaccess ,我想知道是否仅在根目录中使用 .htaccess 就可以阻止来自浏览器针对现有文件或目录的所有请求。

让我们试试这个例子:

RewriteEngine On

RewriteBase /~my_user/my_base/

RewriteRule ^list/$ list.php [L]
RewriteRule ^element_of_list/([a-zA-Z0-9\-]+)/$ element.php?elem_id=$1 [L]

现在,如果我写 http://127.0.0.1/~my_user/my_base/list/ ,这工作正常,但如果我写 http://127.0.0.1/~my_user/my_base/list.php 它仍然有效。我不想要那个。我希望用户在最后一种情况下获得 404 错误。

我们有/etc/apache2/mods-enabled/userdir.conf
<IfModule mod_userdir.c>
        UserDir public_html
        UserDir disabled root

        <Directory /home/*/public_html>
                AllowOverride All
                Options Indexes FollowSymLinks
                <Limit GET POST OPTIONS>
                        Order allow,deny
                        Allow from all
                </Limit>
                <LimitExcept GET POST OPTIONS>
                        Order deny,allow
                        Deny from all
                </LimitExcept>
        </Directory>
</IfModule>

我的第一次尝试是使用 RewriteCond :
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ 404.php [L]

但它不起作用。每个请求最终都重定向到 404.php

更新

所以我设法为目录创建了过滤器:
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !^/~my_user/my_base/$ [NC]
RewriteRule ^(.*)$ 404.php [L]

它的作用是检查请求的路径( REQUEST_FILENAME )是否存在并且它是一个目录,如果它不是我的 RewriteBase,它基本上是 index.php,然后重定向到 404.php

我仍在努力寻找对文件做同样事情的东西。我知道我可以有选择地使用扩展文件名来做到这一点,但我想要一个通用的文件过滤器。

最佳答案

如果我正确理解了您的要求,那么您正在寻找执行以下操作:

# This is a real directory...
RewriteCond %{REQUEST_FILENAME} -f [OR]
# Or it's a real file...
RewriteCond %{REQUEST_FILENAME} -d
# And it's not 404.php...
RewriteCond $0 !=404.php
# And it's not the root
RewriteCond $0 !=""
# And it's not any of the above due to an internal redirect...
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# So cause a 404 response (you could redirect to 404.php if you want)
RewriteRule ^.*$ - [R=404,L]

# Set the 404 error document
ErrorDocument 404 /~my_user/my_base/404.php

请记住,这会阻止所有存在的内容,因此任何图像、样式表或脚本也将发送到 404 页面。如果您只想阻止对 PHP 文件的访问,则 Gumbo's solution 更合适。我认为在这种情况下,您将需要另一个 RewriteCond 以防止循环:
# Make sure the reason this request has a .php is because it was requested
# by the user (and not due to a redirect)
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/[^\s]+\.php
# Make sure we aren't on 404.php already
RewriteRule %{REQUEST_URI} !404\.php$
# We aren't, so redirect to 404.php
RewriteRule ^ 404.php [L]

关于.htaccess - 拒绝使用 .htaccess 直接访问文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3791148/

相关文章:

php - 为什么 $_GET = index.php

apache - .htaccess 防止在浏览器中浏览子目录和更新 URL

node.js - 将外部 URL 重写为内部 URL

php - .htaccess 正在重命名我的 css、img 和 js

php - Mod 重写和 java 脚本弹出窗口

linux - Google Cloud Platform Apache WebServer 表示已达到 "Site Can' t”

ssl - Startcom SSL 的 https 无法正常工作

wordpress - 使用 htaccess 屏蔽 wp-admin 文件夹

javascript - CORS - 不存在 'Access-Control-Allow-Origin' header

php - 安装apc时服务器版本不兼容