Modified: 07th Jul 14 |

Apache/httpd Redirect/RedirectMatch problem

Apache query redirect with special characters

Problem: Redirecting pages/requests with special characters will not work with apache.

I tried to do something like this:

# Moved
Redirect 301 /?p=1
RedirectMatch 301 ^/$

# Gone (everything else)
Redirect 410

But Apache just refuses to take question mark and equal sign into account. I even tried quoting it, and writing the url encoded counterpart.

Reason: Apparently, the rewrite rule only considers the path component, not the query component. the cuery component is the part of the URL that begins with "?".

Solution: Use mod_rewrite, it can send proper response codes too!
The following directives ended up working exactly as i wanted.

rewriteengine on

# articles are moved
RewriteCond %{query_string} ^p=7$
RewriteRule ^/$ [R=301]

# front page is movedRewriteCond %{query_string} ^$
RewriteRule ^/$ [R=301]

# everything else is gone
RewriteRule ^/ [G]

As can be seen, the mod_rewrite engine can be configured with what response codes to send, just like the redirect directives. The [G] means "Gone" (410), while [R=301] means "Permanently Moved" (301).