Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod_rewrite with spaces in the urls

I need to set up some RewriteRules to redirect a URL which has a space in it. I've tried this:

RewriteRule ^article/with%20spaces.html$ /article/without_spaces.html [R=301,L]

... but it doesn't work. Putting in a space instead of %20 causes a 500 Internal Server Error. How do I add a space?

like image 470
nickf Avatar asked Jan 04 '09 10:01

nickf


People also ask

What is rewrite path?

The RewritePath(String) method redirects a request for a resource to a different path than the one that is indicated by the requested URL.

What is mod_rewrite used for?

mod_rewrite lets you create all sorts of rules for manipulating URLs. For example, you can insert values pulled from the requested URL into the new URL, letting you rewrite URLs dynamically.

Where is mod_rewrite so?

The mod_rewrite module is enabled by default on CentOS 7. If you find it is not enabled on your server, you can enable it by editing 00-base. conf file located in /etc/httpd/conf. modules.


5 Answers

Try putting a \ in front of your space to escape it.

RewriteRule ^article/with\ spaces.html$ /article/without_spaces.html [R=301,L]
like image 79
Beau Simensen Avatar answered Sep 29 '22 21:09

Beau Simensen


You can just escape the space with a \

RewriteRule ^article/with\ spaces.html$ /article/without_spaces.html [R=301,L]
like image 24
Rich Adams Avatar answered Sep 29 '22 20:09

Rich Adams


If you want to avoid the complexity of escaping each space (e.g. if you plan to have this file automatically generated), you can simply use quotes:

RewriteRule "^article/with spaces.html$" /article/without_spaces.html [R=301,L]

Furthermore, these quotes can be used to encase any one expected argument:

RewriteRule "^article/with spaces.html$" "/article/without_spaces.html" [R=301,L]
like image 22
Denia Avatar answered Sep 29 '22 22:09

Denia


RewriteRule ^article/with[\ |%2520]spaces.html$ /article/without_spaces.html [R=301,L]

The first option replaces a space while the second replaces hard coded %20 in the url.

like image 41
Abraham Kifle Avatar answered Sep 29 '22 20:09

Abraham Kifle


Ah, I've found a solution: use the regex style to show a space:

RewriteRule ^article/with\sspaces.html$ ...

Though, I suspect that this would match all the other whitespace characters too (tabs, etc), but I don't think it's going to be much of a problem.

like image 20
nickf Avatar answered Sep 29 '22 21:09

nickf