-1

I have the following nginx rewrite rule.

location /search {
             rewrite ^/search/([^/]*)\.html$ /search/?search=$1 break;
            try_files $uri $uri/ =404;
    }

I want this to be like from:

http://test.com/search/?search=nginx

to:

http://test.com/search/nginx.html

thank you very much.

cnst
  • 25,870
  • 6
  • 90
  • 122
dsaint
  • 59
  • 7
  • Thanks for offering the bounty, I hope you find my answer useful. BTW, if you really like it, and want more exposure, make sure to not award the bounty right away, before the grace period starts, because otherwise, the question would go away from the bounty page. Note that accepting an answer, without awarding a bounty, is a good way to ensure both exposure and guarantee that the bounty won't be lost, as the question will continue to be shown on the bounty list until the grace period would start. (Usually, most upvotes for the bounties happen in the last couple of hours.) Thanks, +1! – cnst Jul 25 '17 at 03:16
  • Heh, only a few weeks until an almost identical question on ServerFault! https://serverfault.com/questions/866201/an-optimal-way-of-nginx-rewrite-rule-building-for-pretty-url – cnst Aug 04 '17 at 20:07

1 Answers1

0

You haven't specified which part isn't working. However, it looks like an incomplete solution in any case, as you're missing a full-cycle loop.

Take a look at nginx redirect loop, remove index.php from url and https://serverfault.com/a/568902/110020 — the idea is create a redirect loop, but break it due to the differences in external vs. internal redirect.

Try this, with the full config at https://gist.github.com/cnst/3521404dfdf5cb7b4c526b5c6dff38ff:

location = /search/ {
    if ($arg_search) {
        return  302 /search/$arg_search.html;
    }
    return  200
    "<!DOCTYPE html><title>search</title>
    <form><input name='search'/></form>\n";
}
location /search/ {
    rewrite     ^/search/([^/]*)\.html$     /search/?search=$1  break;
    proxy_pass  http://localhost:7381;
}

The above code will automatically redirect /search/?search=nginx to /search/nginx.html externally, such that the location in the browser will change, but will then process the request with the backend as if no such redirect has ever happened.

cnst
  • 25,870
  • 6
  • 90
  • 122
  • Thanks a lot, this works great, the if function was the missing piece. – dsaint Jul 27 '17 at 09:43
  • @dsaint, cool, thanks! Can you also accept the answer, then? BTW, for the future, you might want to accept instead of award, because now this QA is no longer featured at the bounty list, so, we won't get any more upvotes. :-( – cnst Jul 27 '17 at 17:47