Codeigniter htaccess 没有重定向到 localhost/index.php/no-direct-access

Codeigniter htaccess not redirecting to localhost/index.php/no-direct-access

我想阻止直接访问某个目录中的图像,因此如果用户试图直接访问图像,我会尝试将用户重定向到另一个页面。

RewriteEngine On

RewriteCond %{REQUEST_URI}  \/assets\/images\/user-uploads\/(.)+ [NC]
RewriteRule ^(.*)$ index.php/no-direct-access [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/ [L]

当我拨打 www.example.com/assets/images/user-uploads/image.jpg 时,它给我 404 错误

请帮我解决这个问题。

Direct as in I don't want anyone to view images lying in user-uploaded directory. if anyone dials to view any image in said directory using url like www.sitename.com/assets/images/user-uploads/image.jpg instead of opening the image file in browser they should be redirected to no-direct-access page. if the aforementioned image is part of any file (php or html) then it is okay to render the image.

您的初始方法的问题在于它会阻止 每个 client-side 请求。任何“属于任何文件(php 或 HTML)”的图像也将被阻止。

要仅阻止“直接请求”(即当用户直接在浏览器中键入 URL 时),您可以检查 Referer HTTP 请求 header。这在直接请求时为空,并设置为 referring URL 否则(即 link 被 clicked[=37 的页面=]).

然而,这是不可靠的。用户可以将他们的浏览器配置为不发送 Referer header(因此这些用户将被阻止)。搜索引擎机器人不会发送 Referer header(如果这是一个问题)。对于恶作剧的用户来说,伪造 Referer 以获得访问权限是微不足道的。

“重定向”的另一个“问题”是用户收到 3xx HTTP 响应代码,表明资源已“移动”,而不是不可访问。但是,通过您的“尝试”,您正在 内部重写 请求,因此(如果成功)这将 return 200 OK 状态(除非您手动覆盖它)。

它比 return 403 Forbidden 更可取,并且可能 /no-direct-access 作为自定义 403 错误文档。

例如,请尝试以下操作:

ErrorDocument 403 /index.php/no-direct-access

RewriteEngine On

# Block direct access to the "user-uploads" directory
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/
RewriteRule ^assets/images/user-uploads/ - [NC,F]

# CI front-controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php/ [L]

其中 example.com 是您网站的域名。