The scenario is simple so you shouldn't be able to access a file via a HTTP request unless you're logged in otherwise you get redirected to main page. In this example, we're going to use a dummy PDF file but you can extend types as you wish.


How it works


Assuming that our URL is http://www.inanzzz.com/.



Enable mod_rewrite in Apache


Change AllowOverride None to AllowOverride All in /etc/httpd/conf/httpd.conf file then restart apache server.


# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
AllowOverride All

.htaccess


RewriteEngine On
RewriteCond %{REQUEST_URI} \.(pdf)$ [NC]
RewriteRule ^ validate.php?request_url=%{REQUEST_URI} [L]
# To disable or prevent the directory access/listing
Options -Indexes

validate.php


<?php
session_start();

if (!isset($_SESSION['login'])) {
header ('Location: index.php');
exit();
} else {
// Get server document root
$document_root = $_SERVER['DOCUMENT_ROOT'];
// Get request URL from .htaccess
$request_url = $_GET['request_url'];
// Get file name only
$filename = basename($request_url);

// Set headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename='.$filename);

// Output file content
@readfile($document_root.$request_url);
}

index.php


<h3>HTACCESS controlled site</h3>

<p>You should be logged in in order to access 1.pdf via URL.</p>

<?php
session_start();

echo !isset($_SESSION['login'])
? '<a href="?login">Click here to login</a>'
: '<a href="?logout">Click here to logout</a>';

if (isset($_GET['login'])) {
$_SESSION['login'] = true;
header('location: index.php');
exit;
} elseif (isset($_GET['logout']) && isset($_SESSION['login'])) {
unset($_SESSION['login']);
session_destroy();
header('location: index.php');
exit;
}

// Do something else here if you want

Structure


project-folder
.htaccess
1.pdf
index.php
validate.php

Test


Access to http://www.inanzzz.com/ and click "Login" link. Try to access http://www.inanzzz.com/1.pdf which will successfully let you see the file content. Go back and click "Logout" link. Try to access http://www.inanzzz.com/1.pdf but in this case you'll be redirected to home page instead.