DigM
DigM

Reputation: 519

Redirect specific image to another specific image htaccess - WordPress

I have a WordPress website, where I want to specifically redirect one image to another image. I have tried using a redirection plugin and while this has worked for web pages, it didn't seem to work for my image and it suggested that I needed to add the redirect to my .htaccess file.

So I have tried adding the following:

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
Options +FollowSymLinks
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteRule ^wp-content/uploads/2021/03/ImageA.jpg$ ^wp-content/uploads/2021/03/imageB.jpg [L,R=301]
</IfModule>

# END WordPress

However, this still doesn't seem to work. Is there something that I'm missing?

Upvotes: 2

Views: 1640

Answers (1)

MrWhite
MrWhite

Reputation: 45958

If the original URL/image exists as a physical file then the redirection plugin will not work since the WordPress engine is never initiated.

RewriteRule ^wp-content/uploads/2021/03/TrackClosed.jpg$ ^wp-content/uploads/2021/03/LightningTalks.jpg [L,R=301]

There are a few things potentially wrong with this:

  1. By placing this after the WordPress front-controller it is only going to be processed if the original URL still exists as a physical file. If the source URL does not exist as a physical file then this directive needs to go before the WP front-controller (ie. before the # BEGIN WordPress section).

  2. The target URL, starting with ^ is not valid. You should be explicit and start the destination URL with a slash (ie. root-relative). Although this is not strictly necessary since the RewriteBase directive is defined.

  3. Should this really be an external 3xx redirect or an internal rewrite?

  4. You should avoid editing the code inside the # BEGIN WordPress block since WP itself tries to main this section and any customisations could be overwritten.

Try the following instead, at the top of the .htacess file, before the # BEGIN WordPress section:

RewriteRule ^wp-content/uploads/2021/03/ImageA\.jpg$ /wp-content/uploads/2021/03/ImageB.jpg [R=301,L]

This "redirects" /wp-content/uploads/2021/03/ImageA.jpg (case-sensitive match) to /wp-content/uploads/2021/03/ImageB.jpg. To change this to an internal rewrite then simply remove the R=301 flag.

There is no need to repeat the RewriteEngine directive.

Test with a 302 (temporary) redirect first. You will likely need to clear your browser cache before testing.

Upvotes: 1

Related Questions