2

If I have a file located at http//site.com/files/foo.zip.

How can I rewrite this url to http://site.com/download/foo.zip, so the real URL doesn't show at all in the user's browser/download manager ?

Alex
  • 66,732
  • 177
  • 439
  • 641

2 Answers2

6

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;
Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • The OP probably needs internal rewriting: `[L]`. There's a sense of a need to hide the original URL. `[R]` would essentially expose the original URL by way of the HTTP redirection. – Ates Goral Mar 31 '11 at 00:53
  • well I want to restrict download access to registered users only. I think I would need somehow to check if the user is registered before URL is changed – Alex Mar 31 '11 at 00:55
  • @Alexandra That won't stop an unregistered user from download anything, I'll make an update. – alex Mar 31 '11 at 00:56
  • thank you. I used `dirname(ABSPATH).'/dir/'.$_GET['file']` for the file path. so now to have a nice URL instead of download.php I only need to rewrite the script path – Alex Mar 31 '11 at 01:41
2

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

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291