Intercept request to /wp-content/uploads/random.file

I just ran a test where I uploaded an image to media library, then renamed my root index.php file to break WordPress, but the image I uploaded was still available by accessing it directly with its wp-content/uploads/... URL.

There are no .htaccess files in wp-content or uploads either, which means that, barring any plugins that might do some magic to intercept those URLs, access to those files is direct, not through any PHP.

So, to do what you want you’d need to add an .htaccess rule which would intercept these URL’s and pass them to a PHP script such as WordPress’s index.php. For example something like this in your root .htaccess would do it:

RewriteRule wp-content/uploads/(.*)$ index.php?uploadUrl=$1 [L,NC]

Note: This would have be added above the WordPress block so WP did not overwrite and remove it.

You’d then have to catch those URL’s before WordPress processes them to do whatever it is you’re trying to do, and a good place for that is the template_redirect hook, which gets run before WordPress has started figuring out how to render the page.

So something like:

function hook_upload_url() {
   if (!empty($_GET['uploadUrl'])) {
       // do your thing, path of this file is in $_GET['uploadUrl']
       // perhaps you want to serve a file, or wp_redirect(), then die()
   }
}

add_action( 'template_redirect', 'hook_upload_url' );

Code here is examples of how to achieve what you want, but untested. Please reply with any questions/problems if you do it this way.

Note

  • Doing this is probably a very bad idea as it will cause a whole WP instance to be spun up for every single access to any media, which as above does not happen by default. You’re at risk of putting a ton more load on your server.
  • There might be another or better way to get the URL query param WP style, rather than use $_GET directly

Leave a Comment