You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制文件通过URL直接访问/下载,仅允许PHP/HTML代码触发下载?

Got it, here's a solid approach to achieve exactly what you're asking for—block direct URL access to files like PDFs while allowing downloads via your site's links. Let's break this down step by step:

1. Secure Your File Storage (Critical First Step)

First, move your PDF files outside your web root directory (e.g., /var/www/private_files/ instead of /var/www/html/pdf/). This way, they're completely inaccessible via direct URLs by default, eliminating any chance of accidental exposure.

If you can't move the files (e.g., hosting restrictions), skip to step 2 to lock down the directory with .htaccess.

2. Block Direct Access with .htaccess (For Apache)

If your files have to stay in a web-accessible folder (like /pdf/), create a .htaccess file inside that folder with this code to deny all direct requests:

Order Deny,Allow
Deny from all

Now anyone trying to visit http://example.com/pdf/sample-pdf1.pdf directly will get a 403 Forbidden error.

For Nginx users, add this rule to your server config instead:

location /pdf/ {
    deny all;
}

3. Create a PHP Download Handler

Next, write a simple PHP script (e.g., download.php) that acts as a gatekeeper—it only lets users download files if the request comes from your site (or via a valid token for extra security).

Basic Version (Referer Check)

This checks if the request originated from your website (note: HTTP_REFERER can be spoofed, so use this for low-security needs):

<?php
// Define your site's base URL
$allowed_domain = 'http://example.com';

// Validate request source
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], $allowed_domain) === false) {
    // Redirect to error page or show message
    header('Location: /error-page.html');
    exit;
}

// Sanitize the requested filename to prevent directory traversal attacks
$filename = basename($_GET['file']);
// Path to your private files folder
$file_path = '/var/www/private_files/' . $filename;

// Check if the file exists
if (!file_exists($file_path)) {
    header('HTTP/1.0 404 Not Found');
    echo 'File not found.';
    exit;
}

// Set headers to trigger download
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file_path));

// Send the file to the user
readfile($file_path);
exit;

More Secure Version (Token-Based Validation)

For better security (since referers can be faked), use session-based tokens to verify legitimate requests:

First, generate a token when rendering your download link (in your PHP-powered page):

<?php
session_start();
$target_file = 'sample-pdf1.pdf';
// Create a unique token tied to the user's session and file
$token = md5($target_file . session_id() . time());
// Store the token in the session
$_SESSION['download_tokens'][$token] = $target_file;
?>

<!-- Your download link -->
<a href="download.php?token=<?php echo $token; ?>" download>Download PDF</a>

Then update download.php to validate the token:

<?php
session_start();

// Check for valid token
if (!isset($_GET['token']) || !isset($_SESSION['download_tokens'][$_GET['token']])) {
    header('Location: /error-page.html');
    exit;
}

// Get the filename from the session and invalidate the token
$filename = $_SESSION['download_tokens'][$_GET['token']];
unset($_SESSION['download_tokens'][$_GET['token']]);

// Sanitize and verify file path
$file_path = '/var/www/private_files/' . basename($filename);
if (!file_exists($file_path)) {
    header('HTTP/1.0 404 Not Found');
    echo 'File not found.';
    exit;
}

// Send download headers and file content
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;

Replace your original direct file links with ones pointing to the PHP handler:

<!-- Old link (will not work anymore) -->
<!-- <a href="http://example.com/pdf/sample-pdf1.pdf" download>Download</a> -->

<!-- New link -->
<a href="download.php?file=sample-pdf1.pdf" download>Download PDF</a>

Or use the token-based link from the secure version above.

Now, when users click your site's download link, the PHP script will validate the request and send the file. But anyone trying to access the PDF directly via URL will hit a 403 error or get redirected to your error page.

内容的提问来源于stack exchange,提问作者Amit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:34:49