Nice searching in Wordpress
You may have noticed that all the tags on my posts point to URLs of the form /ob-search/_search+term_
. That’s a reasonably simple bit of mod rewriting. This article is aimed at people who can do that.
I wanted a way for the search box to point to the same pages. I figured I could point the search form at a fake page and redirect (it with a HTTP status code of 302 so it is sent to the browser and the user sees it in his/her address bar) to the nice URL (which would secretly redirect to the real one).
So I came up with the following:
RewriteRule ^fake-search.php?s=(*.)$ /ob-search/$1
It didn’t work. Unfortunately Apache strips of query strings before the get to Rewriting and the reattaches them. So to sort it out I had to hack off the query string with one rule (which is accessed using an environment variable) and then extract the bit I wanted with another rule:
RewriteRule fake-search.php /-%{QUERY_STRING}?
RewriteRule ^/-s=(.*)$ /ob-search/$1 [R=302]
RewriteRule ^/ob-search/(.*)$ /index.php?s=$1
The third rule just does the “simple” redirecting as a said in the beginning.
The ?
appending the query string on to the end afterwards. The hyphen in the first two lines could be anything you want - it’s just something for the second rule to recognise.
To finish it off I altered the search form’s action
attribute to point to fake-search.php
and all was well :) Try it :D