Score:0

NGINX: reverse proxy path to subdomain and append the rest

cn flag

I have the following NGINX configuration file:

server {
  server_name devices.example.org;

  ssl_protocols TLSv1.2;
  ssl_certificate /etc/ssl/web/example.crt;
  ssl_certificate_key /etc/ssl/web/example.key;

  location ~* ^/(.*)(.*)?$ {
    proxy_pass                  http://$1.proxy.tv$2;
    proxy_buffering             off;
    proxy_set_header Host       $http_host;
    proxy_set_header X-Real-IP  $remote_addr;
  }

And I need to proxy all incoming requests to the shown backend, i.e.

  • https://devices.example.org/m123 should proxy to http://m123.proxy.tv
  • https://devices.example.org/m123/favicon.ico should proxy to http://m123.proxy.tv/favicon.ico
  • https://devices.example.org/m123/scripts/something.js?params=bar should proxy to http://m123.proxy.tv/scripts/something.js?params=bar

However, I always get the a Bad Gateway error as a return, and in the logs I get:

[error] 18643#0: *12393 favicon.ico.proxy.tv could not be resolved (3: Host not found)

I assume that my regex somehow malforms the proxy request, but I'm not sure how.

Other combinations that I've tried:

  • location ~* ^/(.*)(?:/(.*))$ proxied to http://$1.proxy.tv/$2$is_args$args
  • location ~* ^/(.*)(?:/(.*))? proxied to http://$1.proxy.tv/$2$is_args$args

Any help is greatly appreciated.

Score:0
us flag

You have two wildcard regular expression capture groups in your location block directive, which means everything is captured into $1.

Based on your requirements, the following location block could work:

location ~ ^/(?<subdomain>[^/]+)/(<path>.*)?$ {
    proxy_pass http://$subdomain.proxy.tv/$path;
    ...
}

For clarity, I am using variable names (<>) in the regular expressions. The [^/]+ is used to capture the first part of URL path component (capture 1 or more characters that are not /).

The reason for the Bad Gateway error is that nginx could not resolve the domain name favicon.ico.proxy.tv. These are couple of reasons why it happens:

  1. favicon.ico.proxy.tv is not registered in DNS.
  2. You haven't configured nginx resolver directive with valid DNS resolvers.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.