简体   繁体   English

只有在登录时才允许访问文件(htaccess?)

[英]Only allow access to files if logged in (htaccess?)

We have a set of files (images/documents) located on one subdomain (A), we then have another subdomain (B) that houses a CRM - both subdomains are hosted on the same server/IP and are subdomains of the same primary domain. 我们在一个子域(A)上有一组文件(图像/文档),然后我们有另一个包含CRM的子域(B) - 两个子域都托管在同一服务器/ IP上,并且是同一主域的子域。

What we're attempting to achieve > Only users logged into B can access files within A. 我们试图实现的目标 >只有登录B的用户才能访问A中的文件。

We've tried a few solutions with htaccess within A eg only allow access to A's files if they have the correct IP. 我们在A中尝试了一些带有htaccess的解决方案,例如,如果他们拥有正确的IP,则只允许访问A的文件。 We also tried writing htaccess to only allow access to A's files if the user has been referred from B's subdomain - however neither of the attempts have worked....it's notable that we're not thoroughly experienced with htaccess! 我们还尝试编写htaccess只允许访问A的文件,如果用户已经从B的子域引用 - 但是这两种尝试都没有起作用......值得注意的是我们对htaccess没有充分的经验!

We're assuming it's an htaccess job, not sure if we can achieve the result by using PHP instead (preferable)? 我们假设它是一个htaccess工作,不确定我们是否可以通过使用PHP来实现结果(更好)?

Any help greatly appreciated. 任何帮助非常感谢。

Here's an example, but needs more improvements: 这是一个例子,但需要更多改进:

On your CRM while starting the session, you need to make it available on all subdomains: 在开始会话时在您的CRM上,您需要在所有子域上提供它:

<?php

// Make session works on all subdomains
session_set_cookie_params(0, '/', '.example.com');
session_start();

Then create an htaccess at the root of (A), with the following contents: 然后在(A)的根目录创建一个htaccess,其中包含以下内容:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ /download.php?path=$1 [L]

This htaccess will make any request to any file on (A) gets processed by download.php . 此htaccess将对(A)上的任何文件的任何请求由download.php处理。

And then create download.php , with the following contents: 然后创建download.php ,其中包含以下内容:

<?php

if(! isset($_SESSION['your_session_id_here'])) {
    http_response_code(401);
    exit('Not allowed!');
}


if(! isset($_REQUEST['path'])) {
    http_response_code(400);
    exit('Invalid request!');
}

define('DOCUMENTS_ROOT', '/path/to/the/documents/');
define('AUTHORIZED_FILE_EXTENSIONS', ['png', 'jpeg', 'jpg', 'pdf', 'doc', 'zip']);

$path = DOCUMENTS_ROOT . $_REQUEST['path'];

$file_ext = pathinfo($path, PATHINFO_EXTENSION);
$file_ext = strtolower($file_ext);
if(! in_array($file_ext, AUTHORIZED_FILE_EXTENSIONS)) {
    http_response_code(401);
    exit('Not allowed!');
}


// We already did this on Htaccess
//if(! file_exists($path)) {
//    http_response_code(404);
//    exit('Not found!');
//}

header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($path));
readfile($path);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM