URL Rewriting in WP

I hate Apache's mod_rewrite!

Anguish

  1. 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?

  2. 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:
    1. _SERVER["REQUEST_URI"]: /tests/foo?bar
    2. _SERVER["REQUEST_URI"]: /tests/dir/foo/bar
      1. _SERVER["QUERY_STRING"]: foo/bar
      2. _GET["foo/bar"]: no value
    3. _SERVER["REQUEST_URI"]: /tests/dir/foo/bar?may=be
      1. _SERVER["QUERY_STRING"]: foo/bar&may=be
      2. _GET["foo/bar"]: no value
      3. _GET["may"]: be
    And
    RewriteRule ^dir/(.*)$ echo.php?p=$1 [QSA,L]
    makes it easier to extract the path, ie: $_GET["p"] => "foo/bar".

But, WordPress?

  1. 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.
  2. 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

  1. Page's ID, or slug?
  2. Parse query string myself, or with WP's "rewrite tags"?
  3. 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