How to Point Static File Requests to Production by Using Redirects on Apache

Let’s run through how (and why) you might point static file requests made in your development or staging environment towards production to take advantage of using assets that are already hosted elsewhere.

Why would you want to redirect certain file requests to another URL?

I’ve worked with projects that have 30GB+ of /uploads, with new uploads happening every day at a very fast pace. In most cases, it just doesn’t make sense to try to keep these assets in sync between different environments—a huge time savings. Another benefit is the obvious savings in storage space for your local machine, cloud-based development/staging environment, or all of the above.

Win win!

Let’s get started — It’s all in the .htaccess file

Head on over and edit your project’s .htaccess file. Most likely, this will be in your project’s root directory.

.htaccess files differ depending on a project’s requirement. In this example, I’m going to use one that’s for a simple WordPress site (a single site installation).

The basic .htaccess file for a WordPress site is like so:

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

Source: https://codex.wordpress.org/htaccess

We’re going to add in the following snippet that will redirect all image requests made in this environment to the production site:

# Redirect all image requests
RewriteRule (.*)\.(gif|jpg|png)$ https://yourdomain.com/$1 [R,L]

As you can see, it’s quite simple really, and the benefits of such can be enormous.

This trick isn’t limited to only images. It can also be applied to almost anything that is static, such as .pdf or .svg files. Let’s expand on our example to include these as well:

RewriteRule (.*)\.(gif|jpg|png|pdf|svg)$ http://yourdomain.com/$1 [R,L]
# BEGIN WordPress
RewriteEngine On
RewriteBase /
# Begin redirect static file requests
RewriteRule (.*)\.(gif|jpg|png|pdf|svg)$ http://yourdomain.com/$1 [R,L]
# End redirect static file requests
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
Wrapping It Up

Did you find this useful? Do you have any ideas for improving this? Be sure to comment down below and share your thoughts.

2 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *