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;
}
2
Answers
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 thelocation
andproxy_pass
values.For example:
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: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 useNote 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 invalidpany
one (an invalid because it does not start with a slash). So usinglocation /google.com/ { ... }
instead will be more safe.You can use the following location to allow exact
/google.com
request URI to be processed too:or a single rewrite rule at the
server
block level:Or you can use a regex matching location and slightly modified rewrite rule: