Nginx Configuration – Fixing URL Matching Issues with Valid Regex

configurationnginx

I'm using npm(Nginx Proxy Manager) to manage my nginx config.

npm has generated this location block:

location  ~*  ^/docker-compose-ui/?(.*)$ {
    set              $upstream http://docker_compose_ui:5000/$1$request_uri;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Scheme $scheme;
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_set_header X-Forwarded-For    $remote_addr;
    proxy_set_header X-Real-IP      $remote_addr;
    proxy_pass       $upstream;



    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
    proxy_http_version 1.1;



    add_header X-testing "matching: $1,  r_uri: $request_uri";
  }

It matches this URL: http://192.168.1.148/docker-compose-ui/

but it doesn't match against any of the page assets so the page loads without any working styling or javascript.

I can see the header I added: X-testing: matching: , r_uri: /docker-compose-ui/

But not on any of the assets, if I try http://192.168.1.148/docker-compose-ui/scripts/directives/actions.js directly, all I get is a 502 bad gateway error.

I've tried a bunch of things, even adding a location to match against the assets:

~* ^/docker-compose-ui/(images/|img/|scripts/|script/|javascript/|js/|bower_components/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico)

But nothing works, nginx refuses to proxy anything other than /docker-compose-ui/.

Why is Nginx appearing to ignore my defined locations and refusing to proxy the assets?

Best Answer

Besides the configuration you provide requires a resolver defined to work properly (which is most likely the cause of HTTP 502 Bad Gateway error), adding $request_uri to the end of your upstream URL is a complete nonsense. Lets look what it would be for the URL you provide as an example:

http://192.168.1.148/docker-compose-ui/scripts/directives/actions.js

Variables used to compose $upstream would have the following values:

$1             scripts/directives/actions.js
$request_uri   /docker-compose-ui/scripts/directives/actions.js

That means the whole $upstream variable (which is set as http://docker_compose_ui:5000/$1$request_uri) would be equal to

http://docker_compose_ui:5000/scripts/directives/actions.js/docker-compose-ui/scripts/directives/actions.js

Did it seems ok to you? I don't think so.

Lets try this one instead:

location ^~ /docker-compose-ui {
    rewrite ^/docker-compose-ui/?(.*) /$1 break;

    proxy_set_header Host               $host;
    proxy_set_header X-Forwarded-Scheme $scheme;
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_set_header X-Forwarded-For    $remote_addr;
    proxy_set_header X-Real-IP          $remote_addr;
    proxy_pass       http://docker_compose_ui:5000;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
    proxy_http_version 1.1;
}