Give access to private files to certain role? I have a few image styles set up. But they are all stored as "private" files. I want to be able to give anonymous users public access to these files, or find some other way by which to generate access to this file. My goal is to provide access to private files for certain anonymous users depending on certain conditions.

I am hiding all images on the server to avoid anyone accidentally gaining access to them, but some "private" images should be viewable if a certain style is applied. For example, I am selling images on my site. The "waterproof" image style should allow any user (including anonymous) user to see the private file preview. But only logged in users should be able to view it with the "high_res" thumbnail.

This is how I generate the URL:

$imageURL = file_create_url($badge-&gt;field_badge_image_image-&gt;entity-&gt;getFileUri());


This url can only be accessed by logged in users. If I try this code, I still get access denied.

$imageURL = ImageStyle::load('farm_logos')-&gt;buildUrl(
    $badge-&gt;field_badge_image_image-&gt;entity-&gt;getFileUri() 
);


Is there no way to generate a URL that is accessible via public? 

I also tried the "hook_file_download":

function mymodule_file_download($uri) { 
    return array(
        "Accept" =&gt; "Accept",
        'Content-Type' =&gt; "image/jpg"
    );
}


But I was hoping this would make all private files public, but unfortunately it did not.
I found the problem. As per this page:

Once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.
For example: you have created a new content type with a file field which stores files in your site's private file directory. Next you create a node from this new content type and attach two new files. When the node is published links to both attached files are visible and anyone who can view the node may download the files. Now, if you unpublish the node, all attached files become inaccessible for download even if you use the direct link to the files that worked when the node was published.
Re-publish the node, and disable the &quot;display&quot; checkbox for one of the files. Save the node. Now one file is accessible for public download and the other is not accessible--even if you have the direct URL for the file that is not listed you will not be able to download this file.

So the problem was that I was expecting you could access a file if you have the right URL, even if that file is used on an UNPUBLISHED node. So to solve my problem I:

Published all the nodes I needed to have access to the image
Used &quot;Rabbit Hole&quot; to hide the nodes from the public