Sinister Beard
Sinister Beard

Reputation: 3680

Bypass .htaccess when using download_url

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 when using the WordPress function download_url to access a file in that directory from within functions.php. Is there a rewrite condition I can use to facilitate this?

Upvotes: 1

Views: 1075

Answers (2)

noahnu
noahnu

Reputation: 3574

You can add another RewriteCond on the QUERY_STRING property.

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

https://wiki.apache.org/httpd/RewriteQueryString

Edit: I misunderstood the question. I thought you were passing download_url in the URL. You could just exclude from your RewriteRule the entire directory where downloadable files are located.

E.g.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !(www.)?example.co.uk/client-area*
RewriteCond %{REQUEST_URI} !\/wp-content\/uploads\/((\.[^\.])|([a-z0-9\-_\+\/]))+$ [NC]
RewriteRule ^.*$ - [R=403,L]
ErrorDocument 403 'http://www.example.co.uk/client-area/'

By the way, I wouldn't really depend on HTTP_REFERER to filter content, it can be easily modified/spoofed by the client. The regex in the RewriteCond I added, will match letters, numbers, dashes, underscores, pluses and forward slashes. It specifically will not match "..". This is to prevent relative URIs from access other files outside of wp-content/uploads. (I think Apache will actually expand the URI and then try to match the expanded URI against your rules.)

Upvotes: 1

anubhava
anubhava

Reputation: 785058

If I understand it correctly you are calling a WP function download_url and want to skip this rule from 403.

The thing is that Web server (Apache) won't know if request is coming due to you calling download_url function.

As a workaround you will need to pass some query parameter to help out mod_rewrite rules but that is not a safe approach as any visitor of your website can also do the same by passing same query paramter.

Upvotes: 0

Related Questions