URL Rewriting in WP
I hate Apache's mod_rewrite!
Anguish
- Trying to set up a dynamic page in WordPress. Need to capture requests of the form /dir/foo/bar/baz, where {foo,bar,baz} are optional. "dir" would be the slug of a page whose template generates dynamic content based on the… URI? Or query string?
-
Intuition didn't seem to work, so debugging with phpinfo() (or Python's cgi.test):
RewriteEngine On RewriteBase /tests/ RewriteRule ^dir/(.*)$ echo.php?$1 [QSA,L] RewriteRule . echo.php [L]
And echo.php (<? phpinfo(INFO_VARIABLES); ?>
) reports:- _SERVER["REQUEST_URI"]: /tests/foo?bar
- _SERVER["REQUEST_URI"]: /tests/dir/foo/bar
- _SERVER["QUERY_STRING"]: foo/bar
- _GET["foo/bar"]: no value
- _SERVER["REQUEST_URI"]: /tests/dir/foo/bar?may=be
- _SERVER["QUERY_STRING"]: foo/bar&may=be
- _GET["foo/bar"]: no value
- _GET["may"]: be
RewriteRule ^dir/(.*)$ echo.php?p=$1 [QSA,L]
makes it easier to extract the path, ie: $_GET["p"] => "foo/bar".
But, WordPress?
- Letting it fall-through with
RewriteRule ^dir/(.*)$ dir/?p=$1 [QSA]
or rewriting to index.php, still gives "/tests/dir/foo/bar", which I guess confuses WP. -
Bah. Been going at it wrong: WP now has a built-in mechanism for URL rewriting. Inserting:
add_rewrite_rule("^dir/(.*)/$", "index.php?p=123&bar=$matches[1]", "top");
into theme's functions.php does the trick. Except…
Issues
- Page's ID, or slug?
- Parse query string myself, or with WP's "rewrite tags"?
- URL prefix hardcoded. Would be nice if WP could manage it, ie, redirect if page's slug changed.
--
The real world is a special case