'apache redirect rule exception for wordpress subfolders

I have a wordpress site with a public part and a private section which only registered users may access. Among other stuff there is a lot of files for download. The "wp-content/uploads" directory contains a mixture of private files for registered users in various subfolders. These private files may only be accessed after logging in. On the other hand,there are publicly available files.

I have tried to solve this by creating a subdir "wp-content/uploads/public" in the "wp-content/uploads" directory and using a .htaccess file in the DocumentRoot folder with rewrite rules as follows:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/public/.* [NC]
 RewriteRule . https://%{HTTP_HOST}%{REQUEST_URI} [L,QSA]
 RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
 RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/.* [NC]
 RewriteRule . https://%{HTTP_HOST}%1/wp-login.php?redirect_to=%{REQUEST_URI} [L,QSA]
</IfModule>

By these rules, I hoped to achieve the following:

When a non-logged-in user tries to access a publicly available file from the directory "wp-content/uploads/public" or its subfolders, the request should succeed without asking for credentials.. Other requests to files in "wp-content/uploads" including its subfolders should be lead to the wordpress login page, so that they can give their wordpress credentials before being redirected to the requested file.

But, it seems as if the rewriting doesn't get to the protected part: requests to the "wp-content/uploads" directory are accepted regardless of the users being logged in or not. It seems as if the first rewrite condition meets all the requests.

Where is my fault?

Thanks in advance Michael



Solution 1:[1]

Relying on Apache to correctly redirect away from private files isn't really the most secure solution.

I would force all requests to your "private" folder to redirect to a file like this, which can then discern whether or not the requester is logged in or not.

You may need to tinker with that file a bit as the original creator was locking down the entire /uploads folder, but it would be a reliable and secure method of achieving what you are trying to do here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mizzy