0

Currently I have some zip files stored in the http root of my php/apache web server.

Currently I can access the files using this:

http://example.com/filename.zip

However, I want to "protect" the access to this files, and they should only be accessible using something like:

http://example.com/key/filename.zip

Could someone help me to create a rewrite rule to do this?

The key is a fixed string. It will be hardcoded in .htaccess rules.


When the user accesses the following URL:

http://example.com/key/filename.zip

He should be able to download the zip file.


When the user accesses the following URL:

http://example.com/filename.zip

He should not be able to download the zip file. He should receive an http error.


My code so far:

RewriteEngine on
RewriteRule ^key/(\w+).zip $1.zip
MrWhite
  • 11,643
  • 4
  • 25
  • 40
dikonubiga
  • 11
  • 3

1 Answers1

0

Your existing code should already serve /filename.zip when accessing /key/filename.zip (although it should be tidied a bit).

To block direct requests to /filename.zip, you can do something like the following before your existing directive:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^/?\w+\.zip$ - [F]

This blocks (403 Forbidden) all direct requests for URLs of the form /filename.zip (in the document root), regardless of whether it maps to an existing file or not.

Alternatively, to send a 404 instead, change the F flag to R=404.

So, in summary:

RewriteEngine On

# Block direct requests to /<filename>.zip
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^/?\w+\.zip$ - [R=404]

# Internally rewrite /key/<filename>.zip to /<filename>.zip
RewriteRule ^/?key/(\w+)\.zip /$1.zip [L]

Remember to backslash escape the dot to match a literal dot.

Note that this unconditionally rewrites all requests for /key/<filename>.zip to /<filename>.zip, regardless of whether /<filename>.zip exists or not. You'll just get a 404 if it doesn't.

The L flag may be required if you have other directives that follow.

I've modified the directives so they will work in the server config (as well as .htaccess).

MrWhite
  • 11,643
  • 4
  • 25
  • 40