首页 > 解决方案 > How can I preserve spaces (%20) when using Apache RewriteRule?

问题描述

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!

标签: apache.htaccessmod-rewrite

解决方案


你可以在你的 RewriteRule 中尝试这个 RegEx 。您可以更改此 URL:

^https:\/\/example\.com\/images\/this(.*)$

 https://example.com/wp-content/uploads/this$1

它可能会起作用。

在此处输入图像描述

如果您只想制作单个图像,则可能只使用\char 和转义元字符,例如%,并且您可能不需要任何特定的正则表达式。您可以通过重定向简单地做到这一点:

^https:\/\/example\.com\/images\/this\%20is\%20a\%20link\%20with\%20spaces\.jpg$  

https://example.com/wp-content/uploads/this\%20is\%20a\%20link\%20with\%20spaces\.jpg

您可能需要清除浏览器缓存,重新启动 apache。

htaccess

您的规则可能如下所示。您可以阅读这篇文章以确保:

RewriteEngine On
RewriteRule ^https:\/\/example\.com\/images\/this(.*)$ https://example.com/wp-content/uploads/this$1 [R,L]

推荐阅读