使用Apache RewriteRule时如何保留空格(%20)?

时间:2019-04-28 22:45:23

标签: apache .htaccess mod-rewrite

我正在尝试使用Apache和.htaccess设置一个相当简单的重定向。简而言之,我有一些包含空格的图像链接,例如:

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

,我只想将这些链接重定向到另一个文件夹,即/ wp-content / uploads /(对于WordPress网站),在该文件夹中我已将图像移至其中,因此,我希望上面的链接重定向到该文件夹​​。 :

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

现在是.htaccess文件中的内容:

RewriteEngine On
RewriteRule "^images\/((.*)\.(.*))$" "/wp-content/uploads/images/$1" [R=301,L]

我尝试使用此规则进行的所有操作(包括[NE][B][BNP])都会从目标位置剥离所有空格,从而导致重定向到此URL,而不是我想要:

https://example.com/images/thisisalinkwithspaces.jpg

我找到并遵循的所有教程都告诉您如何删除空间,而没有一个告诉您使用Apache .htaccess时如何保留空间。和RewriteRule

以后的修改:以下是输出结果: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

这是完整的.htaccess文件:

# 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]

任何帮助,将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:2)

好的,所以我终于弄清楚了!这全都归功于我在.htaccess中添加重定向之前尝试使用的WordPress插件。似乎是该插件中的某种错误,它很可能会逃脱URL并导致剥离文件名中的空格。要获得完整解决方案的最终.htaccess文件是:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# Redirect old images to their new location in /wp-content/uploads/
RewriteRule ^images/(.*)$ /wp-content/uploads/images/$1 [R=301,L]

# Rest of standard WordPress rules
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

谢谢大家的提示和指导!

答案 1 :(得分:1)

您可以在RewriteRule中尝试this RegEx。您可以更改以下URL:

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

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

,它可能会起作用。

enter image description here

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

^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

您的规则可能如下所示。您可以阅读this post来确保:

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