location redirect always with trailing slash... sometimes
Francis Daly
francis at daoine.org
Mon Mar 11 09:03:59 UTC 2019
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 at daoine.org
More information about the nginx
mailing list