Can I use URL rewriting to hide the real file URL?
If I have a file located at http//site.com/files/foo.zip.
How can I rewrite this url to 开发者_C百科http://site.com/download/foo.zip, so the real URL doesn't show at all in the user's browser/download manager ?
I assume you have Apache and mean .htaccess
.
RewriteEngine On
RewriteRule ^download/(.*)$ files/$1 [R,L]
Otherwise if you did want to use PHP, you would need to send those requests to a PHP script anyway with URL rewriting.
Update
I want to restrict download access to registered users only.
This won't do that, your best bet is to move these files above the document root and serve them via PHP.
For example...
<?php
// Get into your system's context so we can determine if the user is logged in.
include 'everything.php';
if ( ! $loggedIn) {
die('Log in mate!'); // Handle this somewhat better :)
}
$file = $_GET['file'];
// Get real path for $file.
$file = basename(__FILE__) . '/above/doc/root/files/' . $file;
if ( ! file_exists($file)) {
die('This file does not exist!'); // And handle this better too.
}
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
For midsize files I would also prefer the download script. It's easier to set up.
But you could still use a RewriteRule approach with some cheating. This necessitates that you create temporary authorization files from PHP:
if ($user_is_authenticated) {
touch("tmp/auth-{$_SERVER['REMOTE_ADDR']}");
}
Then you can protect the real download folder with this simple rule:
RewriteCond ../tmp/auth-%{REMOTE_ADDR} !-f
RewriteRule .+\.zip /denied.html
This approach incurs some management overhead. - You need to clean up these authorization status files once in a while (cronjob). Also using IP addresses is not the optimal approach. It's possible with session cookies too, but more involving: Best strategy to protect downloadable files -php/mysql Apache2 server
精彩评论