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?

  • Possible duplicate of Nginx Rewrite Convert Querystring to Path – Froggiz Dec 18 '15 at 16:57
  • I had looked at that one. The question I come back to is that /blog/ is the root of my blog. Those responses in that other post all have /location/file.asmx. I need the blog to work, and post urls like /blog/post-title/. – TJ Sherrill Dec 18 '15 at 17:54
  • Some of the tags are a single word, some are longer. — what does it mean? – Alexey Ten Dec 18 '15 at 18:06
  • Edited in OP. thanks for the question – TJ Sherrill Dec 18 '15 at 18:11

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 '';
  • I tried variations on that and got 404's. what happens if the tag is only a single word like "bicycle"? – TJ Sherrill Dec 18 '15 at 18:28
  • in this case it will not works, so try first with 2 words, if it work i will modify to works for your case. Are there max 2 words, or can it be (n) words ? – Froggiz Dec 18 '15 at 18:42
  • it can be (n) words. It did not work when I tested on a two word tag. The rewrite you have there resulted in this url: urlt.com/blog/tag/-/?tag=Reliance+Nitro – TJ Sherrill Dec 18 '15 at 18:48
  • ok i did some change can you confirm it works now with 2 parameters ? – Froggiz Dec 18 '15 at 18:55
  • that resulted in: url.com/blog/tag/- – TJ Sherrill Dec 18 '15 at 18:58

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.