I’m trying to setup a rather simple redirect using Apache and .htaccess. In short, I have some image links which contain spaces, for example:
https://example.com/images/this%20is%20a%20link%20with%20spaces.jpg
and all I want is to redirect these links to another folder, namely in /wp-content/uploads/ (for a WordPress site), where I have moved the images, therefore I want the link above to redirect to this one:
https://example.com/wp-content/uploads/this%20is%20a%20link%20with%20spaces.jpg
Here’s what I have in the .htaccess file now:
RewriteEngine On
RewriteRule "^images/((.*).(.*))$" "/wp-content/uploads/images/$1" [R=301,L]
Everything I tried around this rule (including [NE]
, [B]
, [BNP]
), strips all the spaces from the destination, resulting in a redirect to this URL, which is NOT what I want:
https://example.com/images/thisisalinkwithspaces.jpg
All the tutorials that I found and followed tell you how to remove spaces and none of them tells you how to preserve spaces when using Apache, .htaccess
and RewriteRule
.
Later edit: Here’s the output of: curl -v https://example.com/images/this%20is%20a%20link%20with%20spaces.jpg
> GET /images/this%20is%20a%20link%20with%20spaces.jpg HTTP/1.1
> Host: example.com
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Date: Mon, 29 Apr 2019 21:17:14 GMT
< Server: Apache
< Expires: Wed, 11 Jan 1984 05:00:00 GMT
< Cache-Control: no-cache, must-revalidate, max-age=0
< X-Redirect-By: WordPress
< Location: https://example.com/wp-content/uploads/images/thisisalinkwithspaces.jpg
< Content-Length: 0
* Connection #0 to host example.com left intact
And here’s the complete .htaccess
file:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
RewriteEngine On
RewriteRule "^images/((.*).(.*))$" "/wp-content/uploads/images/$1" [R=301,L]
Any help with this would be much appreciated, thank you!
2
Answers
Ok, so I managed to finally figure it out! This was all due to a WordPress plugin that I tried to use before adding the redirects in
.htaccess
. It seems to be some sort of bug in that plugin, which probably escapes the URL's and results in stripping down the spaces in the file names. The final.htaccess
file to achieve a fully working solution, was this:Thank you all for your hints and guidance!
You might try this RegEx in your RewriteRule. You might change this URL:
to
and it might work.
If you only want to do that single image, you might only use char and escape metachars such as %, and you may not need any specific regex. You can simply do that by redirecting:
to
You might need to clear your browser cache, restart your apache.
htaccess
Your rule may look like this. You may read this post to make sure: