nginxurl-rewritinghttp-redirectngx-http-rewrite-module

nginx rewrite query string $args to .html URL (w/o backend support)


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.


Solution

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