i want to change my recived uri inside the Nginx location.
this is the url recived to my Nginx | >>> mywebsite.com/google.com/about
and its what i want | >>> cut google.com from uri
and just only send /about to my proxy_pass
/about in uri is something dynamic and it can be anything
this is my config
location /google.com {
rewrite # This is where I do not know what to do
proxy_pass http://google.com;
proxy_set_header Host $host;
}
CodePudding user response:
If you append an "optional URI" to the proxy_pass
value, the request will be modified before passing upstream. See the documentation for details.
You want to substitute /google.com/
with /
, so you should append a trailing /
to both the location
and proxy_pass
values.
For example:
location /example.com/ {
proxy_pass http://example.com/;
}
CodePudding user response:
To complete the Richard's answer, there are two techniques to change an URI that to be passed to the upstream.
With a prefix location, you can strip the prefix specifying another URI with a
proxy_pass
directive, like already shown:location <old_prefix> { proxy_pass <scheme>://<upstream><new_prefix>; }
This way an old prefix will be stripped from the beginning of the request URI, and a new prefix will be added instead.
You can use a
rewrite
rule to modify a request URI whatever way you want to. To strip some prefix like/google.com
you can uselocation /google.com { rewrite ^/google\.com(.*) $1; proxy_pass <scheme>://<upstream>; }
Note that no additional URI part should be specified after the upstream name for the
proxy_pass
directive in this case.
The first one can be used only with prefix location. However it is more performant than the second one and should be preferred whenever possible. On the other hand the second is the only one that can be used in the regex matching or named locations.
There is an important caveat with the second example. Any proper request URI should start with a slash. However used prefix location will match anything started with /google.com
, e.g. /google.company
and the rewritten URI will be an invalid pany
one (an invalid because it does not start with a slash). So using location /google.com/ { ... }
instead will be more safe.
You can use the following location to allow exact /google.com
request URI to be processed too:
location = /google.com {
rewrite ^ /google.com/ last;
}
or a single rewrite rule at the server
block level:
rewrite ^/google\.com$ /google.com/;
Or you can use a regex matching location and slightly modified rewrite rule:
location ^ /google\.com(?:/|$) {
# ensure the rewritten URI will start with a slash
rewrite ^/google\.com/?(.*) /$1;
proxy_pass <scheme>://<upstream>;
}