Nginx rewrite of url with query string

nginxrewrite

I have been googling for a good while and can't figure this one out. It seems simple, and I am sure it is, but I am not a server expert.

My url is: http://www.example.com/blog/?tag=Word1+Word2

Some of the tags are a single word (ex: bicycle), some are longer (ex: Two wheel bicycle).

I need this url to be output as: example.com/blog/tag/word1-word2/

How can I get a rewrite to achieve this?

Best Answer

You should send - in your query instead of + to get same format and make an easier request :

location ~ /blog/ {
    if ($args ~* "tag=(.*)") {
        set $w1 $1;
        rewrite .* /blog/tag/$w1/? permanent;
    }
}

Based on the link i posted

? at the end will remove the query string parameters (from rewrite doc )

If you specify a ? at the end of a rewrite then Nginx will drop the original $args (arguments)

another to achieve it is to set args to nothing:

set $args '';