Welcome! Log In Create A New Profile

Advanced

Re: location redirect always with trailing slash... sometimes

Francis Daly
March 11, 2019 05:04AM
On Fri, Mar 08, 2019 at 09:58:19AM +0100, Hans Schou wrote:

Hi there,

> I found a solution (after reading the manual)
> http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

Great that you found a solution that works for you.

> > Example of required redirect:
> > http://ex.org/foo -> https://ex2.org/foo/ # Nx solves the bug here
> > http://ex.org/foo/ -> https://ex2.org/foo/
> > http://ex.org/foo/?id=7 -> https://ex2.org/?id=7
> >
>
> "rewrite" is the way to go.
> To change /foo or /foo/ to /foo/ and don't change the rest, this will do it:
> location ~ /(foo|bar) {
> rewrite ^(/[^/]+)/? https://ex2.org$1/ permanent;
> }

Just as an aside: that location will also redirect /foox to /foox/,
/foo/x to /foo/, and /x/foo to /x/.

It will keep any ?k=v part in the original request, in the redirected one.

If you want to limit it to just "/foo", "/foo/", "/bar", and "/bar/",
(with optional ?k=v) then you will want to anchor some regexes using ^
and $.

For example:

location ~ ^/(foo|bar)/?$ {
rewrite ^(/[^/]+)/? https://ex2.org$1/ permanent;
}

> If any path should be handled this way:
> location / {
> rewrite ^(/[^/]+)/? https://ex2.org$1/ permanent;
> }

That will do the same -- any request of the form /word or /word/x (where
"word" does not include "/") will be redirected to /word/

rewrite ^(/[^/]+)/?$ https://ex2.org$1/ permanent;

would only redirect requests of the form /word or /word/


Note in particular:

a request for /foo/?id=7 will be redirected to /foo/?id=7, and not to /?id=7.

So that does not match your third requirement as-stated.

(I suspect that you want it to go to /foo/?id=7, and your requirement
is incorrect; so what you have does do what you want.)

Cheers,

f
--
Francis Daly francis@daoine.org
_______________________________________________
nginx mailing list
nginx@nginx.org
http://mailman.nginx.org/mailman/listinfo/nginx
Subject Author Posted

location redirect always with trailing slash... sometimes

hsc@miracle.dk March 07, 2019 08:58AM

Re: location redirect always with trailing slash... sometimes

hsc@miracle.dk March 08, 2019 04:00AM

Re: location redirect always with trailing slash... sometimes

Francis Daly March 11, 2019 05:04AM



Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 112
Record Number of Users: 6 on February 13, 2018
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready