I've got the following .htaccess file in my a custom directory in Uploads called client.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !(www.)?example.co.uk/client-area*
RewriteRule ^.*$ - [R=403,L]
ErrorDocument 403 'http://www.example.co.uk/client-area/'

So if someone tries to access a file in the uploads/client/ directory from anywhere else other than the client-area page, they get redirected.

However, I want to ignore this when I'm using download_url to access a file in that directory. Is there a rewrite condition I can use to facilitate this?

  • This problem has been solved with very WordPress specific code. I have no idea what the point of these close votes is. – fuxia Apr 12 '16 at 7:26
up vote 2 down vote accepted

You can inject a made-up referer into WordPress’ HTTP request by filtering pre_http_request. All you need is a simple class like this (untested!):

class FakeWpReferer
{
    private $referer;

    private $url;

    private $is_regex;

    /**
     * @param string $referer
     * @param string $url URL to fake the referer for.
     * @param bool   $is_regex Is $url a regular expression?
     */
    public function __construct( $referer, $url, $is_regex = FALSE )
    {
        $this->referer  = $referer;
        $this->url      = $url;
        $this->is_regex = $is_regex;
    }

    /**
     * @wp-hook pre_http_request
     * @param   array $args
     *
     * @return array
     */
    public function inject( array $args, $url )
    {
        if ( $this->match_url( $url ) )
            $args['headers']['Referer'] = $this->referer;

        return $args;
    }

    /**
     * @param string $request_url
     *
     * @return bool
     */
    private function match_url( $request_url )
    {
        if ( ! $this->is_regex )
            return $request_url === $this->url;

        return (bool) preg_match( $this->url, $request_url );
    }
}

And then register it as a filter:

$fake = new FakeWpReferer(
    'http://example.co.uk/client-area',
    '~^http://www.example.co.uk/uploads/~',
    TRUE
);
add_filter( 'pre_http_request', [ $fake, 'inject' ], 10, 2 );

Then you can use download_url(), and WordPress will use your custom referer. Be aware that everyone else can fake referers too, so your "protection" isn't really one.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.