Apache rewrite rules and special characters

Posted by Massimo on Server Fault See other posts from Server Fault or by Massimo
Published on 2010-05-20T14:32:45Z Indexed on 2010/05/20 14:41 UTC
Read the original article Hit count: 385

I have a server where some files have an actual %20 in their name (they are generated by an automated tool which handles spaces this way, and I can't do anything about this); this is not a space: it's "%" followed by "2" followed by "0".

On this server, there is an Apache web server, and there are some web pages which links to those files, using their name in URLs like http://servername/file%20with%20a%20name%20like%20this.html; those pages are also generated by the same tool, so I (again!) can't do anything about that. A full search-and-replace on all files, pages and URLs is out of question here.

The problem: when Apache gets called with an URL like the one above, it (correctly) translates the "%20"s into spaces, and then of course it can't find the files, because they don't have actuale spaces in their names.

How can I solve this?

I discovered than by using an URL like http://servername/file%2520name.html it works nicely, because then Apache translates "%25" into a "%" sign, and thus the correct filename gets built.

I tried using an Apache rewrite rule, and I can succesfully replace spaces with hypens with a syntax like this:

RewriteRule    (.*)\ (.*)      $1-$2

The problem: when I try to replace them with a "%2520" sequence, this just doesn't happen. If I use

RewriteRule    (.*)\ (.*)      $1%2520$2

then the resulting URL is http://servername/file520name.html; I've tried "%25" too, but then I only get a "5"; it just looks like the initial "%2" gets somewhat discarded.

The questions:

  • How can I build such a regexp to replace spaces with "%2520"?
  • Is this the only way I can deal with this issue (other than a full search-and-replace which, as I said, can't be done), or do you have any better idea?

© Server Fault or respective owner

Related posts about apache

Related posts about mod-rewrite