W3 Total Cache, RackSpace Cloud Files, and Forcing Downloads

I’m using W3 Total Cache’s CDN connection to RackSpace CloudFiles to serve severall hundred media files. My goal is to get the files to download in the user’s browser, rather than stream. According to the CloudFiles Documentation (http://docs.rackspacecloud.com/files/api/v1/cf-devguide-20111115.pdf) I can set the Content Disposition headers.

Does anyone know how this can be done via W3 Total Cache or, perhaps, around with it? Or, alternatively, do you know of another way to force downloads for files served via the CDN?

Related posts

Leave a Reply

1 comment

  1. This can be broken down to a simple task by adding a custom filter.

    You will need to add the following to the _send_request method within the CF_Http class in cloudfiles_http.php line 1283.

    $headers = $this->_make_headers($hdrs);
    //Add this line below
    $headers = apply_filters('cloudfiles_headers', $headers, $url_path, $method);
    

    This will give you access to the headers from a plugin rather than making large edits to W3TC.

    Within your plugin, you can create a function like this:

    add_filter('cloudfiles_headers', 'wpse_42273_cloudfiles_headers', 0, 3);
    function wpse_42273_cloudfiles_headers($headers, $url_path, $method){
        if($method != 'GET')
             return $headers;
        if(preg_match_all('~^.*/(.+.(jpg|jpeg|png|gif|pdf|doc|docx|csv))$~i', $url_path, $matches)){
            $filename = $matches[1][0];
            $headers[] = "Content-Disposition: attachment; filename=$filename";
        }
        return $headers;
    }
    

    This will add the proper header to force the download if W3TC is fetching an object with a file extension listed in the regex above. This is a good way to control what files are served in the browser and what files have to be downloaded.

    You can try this out in a plugin I created for your convenience. This may need some tweaking, but this is how I feel you should approach the issue.

    Download the plugin here: http://3-3.me/K4SL

    As a final note, this obviously edits the core of the W3TC plugin (though with just one line of code). This isn’t a best practice, but it will work for you. This means any upgrade will override your changes. It might be prudent to rename the plugin (create a fork on your system) so WordPress doesn’t try to update it.

    Hope this helps you out!