How To Protect Media Files Uploaded to WordPress — Speckyboy

How To Protect Media Files Uploaded to WordPress — Speckyboy

The WordPress Media Library is a handy tool for managing images, documents, and multimedia content. It arranges uploaded files into date-based folders and creates multiple image sizes. All great features for a basic website.

There are a few drawbacks, however. The content management system’s (CMS) predictable file structure makes it easy to guess where a file is stored. For instance, a UK budget document leaked before its official release. How did this happen? A journalist was able to guess the file name based on last year’s version:

The BBC was able to access the PDF version of the OBR’s key report at 11:45 on Wednesday by replacing the word ‘March’ with ‘November’ in the web address of a previous edition.

Search engines can also index your site’s media files. This can be a benefit to your SEO strategy, but it’s not always desirable. Consider a membership website that requires registration to access specific files. A user may stumble upon a file via search, defeating the purpose of hiding files behind a login.

None of this means that there’s a security flaw. Rather, WordPress wasn’t built with private media storage in mind. Thankfully, there are easy ways to improve media file security.

Let’s review some tools and techniques for protecting your WordPress media files. They’ll keep your files away from prying eyes and might even save you some hosting bandwidth.

Available Methods of File Protection

The first thing to know about protecting your media files is that there are multiple types of protection. The method(s) you use will depend on your specific needs. We’ll break this section down by common scenarios.

Note that none of the following options will guarantee file security in high-stakes situations such as the UK government leak above. Rather, they are basic measures that will make it harder for someone (or something) to access your files.

With that in mind, here are a few ways to improve file security.

Block Direct File Access From Outside Sites (Hotlinking)

Let’s say you have a large PDF file on your website. By default, an external website could link directly to that file (a.k.a. hotlinking). It may seem harmless, but every time a user clicks that link, the file access counts against your hosting bandwidth. Even worse, the user never visits your website.

The solution is to block hotlink access at the server level. Add the following snippet to your website’s .htaccess file:

# Deny direct access to uploads unless navigated from your  site (change example.com to your domain name)
<IfModule mod_rewrite.c>
RewriteEngine On

# Only apply to files inside uploads directory
RewriteCond %{REQUEST_URI} ^/wp-content/uploads/ [NC]

# Allow requests from your own domain
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/  [NC]

# Block direct access to specified file types
RewriteRule \.(mp3|mp4|pdf|zip)$ - [F,NC,L]

</IfModule>

If your website runs on an NGINX server, add this snippet to the nginx.conf file:

# Deny direct access to uploads unless navigated from your  site (change example.com to your domain name)
# File types protected: mp3, mp4, pdf, zip
  location ~* ^/wp-content/uploads/.*\.(pdf|zip|mp4|mp3)$ {
  
	valid_referers  none blocked server_names *.example.com example.com;
    if  ($invalid_referer) {
  return 403;
  }
}

Be sure to change example.com to match your domain name and edit the included file extensions to match your needs.

Note: We don’t recommend protecting image files this way, as it may lead to undesirable results. For instance, you won’t be able to include images or file links from the server in your email newsletter without adding some exceptions to the code above.

Prevent Search Engines From Indexing Your Media Files

Uploaded WordPress media files can easily end up in search results. This can be undesirable for a few reasons:

  • Direct links to large files can eat up bandwidth.
  • Users aren’t visiting your website, just downloading files.
  • Members-only files could be exposed to the public.

Part of any file protection strategy should include preventing (or discouraging) search engine indexing. As such, there are a few methods to implement.

First, we can add the following to our site’s robots.txt file to discourage crawling of the /wp-content/uploads/ folder:

User-agent: *
Disallow: /wp-content/uploads/

This won’t prevent indexing of your files, just crawling. The main benefit is reducing the load on your server.

To fully prevent indexing, we can use the X-Robots-Tag header.

For Apache servers, add this snippet to your site’s .htaccess file:

# Prevent indexing of media files in /wp-content/uploads/
<IfModule mod_headers.c>
<FilesMatch  "\.(pdf|doc|docx|xls|xlsx|ppt|pptx|zip|rar|7z|mp3|m4a|wav|mp4|mov|avi|webm)$">
Header always set  X-Robots-Tag "noindex, nofollow, nosnippet, noarchive"
</FilesMatch>
</IfModule>

NGINX users can add this to their nginx.conf file:

# Prevent indexing of media files in /wp-content/uploads/
  location ~*  ^/wp-content/uploads/.*\.(pdf|doc|docx|xls|xlsx|ppt|pptx|zip|rar|7z|mp3|m4a|wav|mp4|mov|avi|webm|jpg|jpeg|png|gif|webp|svg)$  {
  add_header  X-Robots-Tag "noindex, nofollow, nosnippet, noarchive" always;
  }

The above methods will reduce bot traffic and reduce the likelihood that your files will appear in search results.

Prevent Access to WordPress Attachment Pages

By default, WordPress creates a post for every media file you upload. It may come in handy for some niche use cases, but it is most often a forgotten feature. Without further action, these posts can be indexed by search engines.

Some SEO plugins, such as Yoast SEO, RankMath, and All in One SEO, offer settings to disable attachment pages. This is the simplest way to prevent search engines or users from accessing them.

Short of that, you can also use a code snippet in your theme’s functions.php file or a custom plugin. We’ll share a couple of them that cover common scenarios.

Return a 404 Error on Attachment Pages:

If you’d like to deny access to attachment pages, the following snippet will do just that. Visitors will see a 404 page, rather than the attachment.

<?php
  /**
  * Force attachment  pages to 404.
  */
  add_action( 'template_redirect', function () {
  if ( !  is_attachment() ) {
  return;
  }
  
  global  $wp_query;
  $wp_query->set_404();
  status_header(  404 );
  nocache_headers();
  
  // Load  your 404 template.
  include  get_query_template( '404' );
  exit;
  } );

Redirect Attachment Pages to Parent Post:

Here’s a slightly different approach that redirects users to the attachment’s parent post. This is handy for blogs and other online publications looking to ensure users see their content, rather than media files.

<?php
  /**
  * Redirect attachment  pages to their parent post when available.
  */
  add_action( 'template_redirect', function () {
  if ( !  is_attachment() ) {
  return;
  }

  $attachment_id  = get_queried_object_id();
  $parent_id     = wp_get_post_parent_id( $attachment_id );
  if (  $parent_id ) {
  wp_safe_redirect(  get_permalink( $parent_id ), 301 );
  exit;
  }

  // No  parent: redirect to file URL if it exists.
  $url =  wp_get_attachment_url( $attachment_id );
  if ( $url  ) {
  wp_safe_redirect(  $url, 301 );
  exit;
  }
  wp_safe_redirect(  home_url( '/' ), 302 );
  exit;
  } );

If you don’t need WordPress attachment pages, there’s no reason to keep them around. Thankfully, you have several options for giving them the heave-ho.

Use a Plugin for Media File Protection

You can also use a plugin to protect your WordPress media files. The right plugin can do some or all of the above functions to keep your files safer.

For example, Download Monitor offers multiple functions, including file protection. Among its features:

  • Disable or enable specific folders for file downloads.
  • Create randomly-generated URLs for files you want to protect.
  • Attempting to access a file directly will result in a 404 error.
  • Require users to log in before accessing a file.
  • Keep track of how many times a file has been downloaded.

The free version of the plugin covers common use cases. A premium version goes the extra mile by integrating with popular form plugins and adding CAPTCHA protection.

Meanwhile, many membership plugins come with some form of file protection. Check out the plugin’s documentation to see what’s available.

The Download Monitor plugin offers file protection features

Take Control of Your Files and Gain Peace of Mind

There are several reasons for locking down your WordPress media files, even if you aren’t posting sensitive information. For one, the rise of AI bot traffic means higher bandwidth usage. Restricting access to large files can prevent surprise charges on your hosting bill.

Plus, media files and attachment pages can be taken out of context. A simple redirect can help by pointing users toward your content. That could be the difference between a one-time visitor and a loyal reader. Say hello to lower bounce rates!

The above solutions are easy to implement into your existing website. What’s more, they bring a little peace of mind. You won’t have to worry about the wrong people accessing your files or causing a traffic nightmare on your server.

Consider your file protection needs and how they might impact your SEO strategy. From there, you can create a plan that works for you.



Top

Share this post :

Facebook
Twitter
LinkedIn
Pinterest

Create a new perspective on life

Your Ads Here (365 x 270 area)
Latest News
Categories

Subscribe our newsletter

Stay updated with the latest tools and insights—straight from ToolRelay.