Reverse proxying with URL Rewrite
Francis Daly
francis at daoine.org
Sun Aug 6 08:21:03 UTC 2023
On Wed, Aug 02, 2023 at 01:42:46PM +0300, O G wrote:
Hi there,
> I would like to reverse proxy the following:
>
> https://test.us/citizensolutions/AB* to *https://*AB*.test.us/ and all the
> subdirectories so that
> all files like https://test.us/citizensolutions/AB/css/*.css reverse proxy
> to https://*AB*.test.us/css/*.css
>
> AB in the above example can be any dynamic input that nginx needs to treat
> as a variable.
Use "map" to create the variables that you want, and then later use
the variables.
You say "any dynamic input"; I'm going to use "up to the next slash,
which must be present"; and you will want to decide how you want to
handle the cases of "AB is empty" or "AB is index.html" and the like.
Strictly, I'd use "map" to create one variable, and a (pcre) regex named
capture group to create the other, like so:
===
map $request_uri $the_bit_after_the_prefix {
~/citizensolutions/([^/]*)(?<the_rest_of_the_request>/.*) $1;
default "";
}
===
(http://ninx.org/r/map)
And then for testing, something like
===
location = /citizensolutions/ {
return 200 "Nope; try again\n";
}
location ^~ /citizensolutions/ {
return 200 "Would use $the_bit_after_the_prefix, $the_rest_of_the_request\n";
}
===
and then when you are happy that the "Would use" is showing you what you
expect in all cases you care about, replace that location{} content with
===
if ($the_bit_after_the_prefix = "") {
return 301 $request_uri/;
}
proxy_pass https://$the_bit_after_the_prefix.test.us$the_rest_of_the_request;
===
You are effectively telling your nginx to resolve-and-access a dns name
provided by the user, so you'll want to be happy that your nginx can do
that, or the users will see 502 errors.
Good luck with it,
f
--
Francis Daly francis at daoine.org
More information about the nginx
mailing list