Vera
Vera

Reputation: 401

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

Upvotes: 3

Views: 3577

Answers (3)

mkvalsvik
mkvalsvik

Reputation: 21

I was trying to convert from a URL like this:

http://java.scandilabs.com/faq?key=Contents_of__gitigno

To a URL like this:

http://scandilabs.com/technology/knowledge/Contents_of__gitigno

Andrew's response above worked for me with the addition of a question mark at the end to discard the original query string:

RewriteCond %{HTTP_HOST} ^java
RewriteCond %{QUERY_STRING} ^key=(.+)$    
RewriteRule ^(.*)$ http://scandilabs.com/technology/knowledge/%1? [R=301,L]

Note if you're on apache 2.4 or higher you can probably use the QSD flag instead of the question mark.

Upvotes: 0

Gumbo
Gumbo

Reputation: 655785

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]

Upvotes: 5

Andrew Moore
Andrew Moore

Reputation: 95454

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]

Upvotes: 7

Related Questions