0

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.

Vapire
  • 105
  • 3

1 Answers1

0

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.
Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
  • I am receiving an error that the "path" variable is unknown, do I need to define this somewhere beforehand? – CoopDaddio Sep 03 '22 at 09:48
  • My answer had an error, I have fixed it. The `?` was missing, which meant that capture to `$path` variable did not work. – Tero Kilkanen Sep 03 '22 at 19:01