Disabling direct access to images using .htaccess

I have added the following rewrite rule to my .htaccess (above the previous rewrite rule):

RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L]

You presumably have another .htaccess file in the /wp subdirectory that contains the main WordPress directives (ie. # BEGIN WordPress etc.).

You should be adding the above rule to the /wp/.htaccess file, not the one in the root.

When accessing a URL of the form /wp/... the mod_rewrite directives in the root .htaccess file are completely overridden by the mod_rewrite directives in /wp/.htaccess (by default). The mod_rewrite directives in the root .htaccess file are not even processed, since mod_rewrite directives are not inherited by default.

The dl-file.php script should then be in the root of the WordPress installation, not in the document root.


Aside:

However, since I installed WordPress in a subdirectory, the image path actually is .../wp/wp-contents/uploads/image.jpg.

Although this would imply you have a mismatch of URLs… some containing the /wp subdirectory and some (your static assets) not.

The first rule you posted rewrites requests to the /wp subdirectory for any request where it is omitted. (The .htaccess file in the /wp subdirectory ensures it does not rewrite requests that already contain /wp.)

You should either:

  • Include /wp in all your URLs

  • Omit /wp from all your URLs.

You currently appear to have a mixture of both.