Q:

.htaccess mod_rewrite: rewriting querystring to path

How could I use a rewrite to change:
/?tag=foo 
To:
/tag/foo
I tried:
RewriteCond %{QUERY_STRING} ^tag=(.+)$
RewriteRule ^(.*)$ http://www.example.com/tag/$1 [L]

But it did not work.

A:

Try the following:
RewriteCond %{QUERY_STRING} ^tag=(.+)$
RewriteRule ^(.*)$ http://www.example.com/tag/%1 [L]

Usually, rewrites are used to achieve the opposite effect. Are you sure you don't really want to do the following?
RewriteRule ^tag/(.+)$ index.php?tag=$1 [L]

A:

To avoid recursion, you should check the request line instead as the query string in %{QUERY_STRING} may already have been changed by another rule:
RewriteCond %{THE_REQUEST} ^GET\ /\?(([^&\s]*&)*)tag=([^&\s]+)&?([^\s]*)
RewriteRule ^(.*)$ /tag/%3?%1%4 [L,R=301]

Then you can rewrite that requests back internally without conflicts:
RewriteRule ^tag/(.*) index.php?tag=$1 [L]

