map with preserving the URL

Francis Daly francis at daoine.org
Mon Apr 8 21:40:13 UTC 2019


On Tue, Apr 02, 2019 at 05:00:19AM -0400, DieterK wrote:

Hi there,

> I'm trying to make the URLs on my site more "friendly" with map, but I don't
> understand the right way.

> location / {
>   if ($new) {
>      rewrite ^ $new redirect;

"redirect" there means "send a http redirect to the client, so that
the client will make a fresh request using the new url". Which means
"the browser url bar will change", as you see.

> The rewriterules.map looks like this:
> /product/foo /product.php?id=100;
> /product/bar /product.php?id=200;

> I already tried it with break instead of redirect, unfortunately it doesn't
> seem to work. (error 500)
> 
> What's the right way to do this?

In principle, replacing your "redirect" with "last" should Just Work. But
there is a separate issue, that when nginx does an internal rewrite,
only an explicit ? in the rewritten string causes the request to be
parsed as "url with query string".

Merely having a ? in the expanded-variable, is not enough.

So, one option could be to "proxy_pass http://127.0.0.1$new;" (where the
scheme://host:port refer to this nginx server -- change as necessary)
instead of "rewrite" -- that is sort-of like an "internal" version of
the redirect. But it is probably overkill, if you can use the next
option instead:

Another option could be to change your map so that you have one variable
that is the query string (id=100; id=200; etc) and another variable that
is the url (/product.php); then you can "rewrite ^ $new?$newquery
last;", and it should do what you want.

(If all of your rewrites will go to /product.php, then you can hardcode
that bit and stick with the single variable.)

With this second option, you could also choose to move the "if($new)"
stanza outside of "location /", and have it at server level. I don't
think it is necessary; but it might be more efficient, depending on the
fraction of requests that set the variable.

Good luck with it,

	f
-- 
Francis Daly        francis at daoine.org


More information about the nginx mailing list