Technomancy

Entries tagged “web”

How to easily force lots files to be downloaded in Apache

written by rory, on Jan 14, 2010 11:23:00 AM.

I had a website, serving up many files. Sometimes you want to 'encourage' a user to download a file instead of their browser displaying a file. You can do this by setting the "Content-Disposition" header. However I had thousands of files that I wanted to force the user to save instead of display. I also needed to be able to let people display them normally.

I came up with this solution, by adding the following to my apache configuration file.

    Alias /download /path/to/my/docroot
    <Location /download>
        SetEnvIf Request_URI "^.*/([^/]*)$" FILENANE=$1
        Header set "Content-disposition" "attachment; filename=%{FILENANE}e"
        UnsetEnv FILENAME
    </Location>

If I go to http://www.example.com/dir1/something/myfile.jpg, then it will display the image in my web browser, however if I go to http://www.example.com/download/dir1/something/myfile.jpg, it will automatically add in the correct HTTP header to force the file to be downloaded. It will also include the correct filename (in this case "myfile.jpg")

It works by adding a new alias for your DocRoot ("/download") and then for all requests that start with that, it'll scan the requested URL and pull out the filename into an apache environment variable. Then a new apache header is added to the response based on this filename to tell the browser to download the file.

There are a few other ways to do this. One solution was to write a simple PHP wrapper script that will add the header and then read the file in and write it out to the user. There are some advantages to this apache header solution. Since apache just thinks it's sending a normal file, it will add the correct ETag or Content-Length HTTP headers.