variablesnginxstaticproxypassserver-name

Nginx reverse proxy didnt load site correctly


I have an nginx configuration which listens to any subdomain *.mydomain.com, and I want to use subdomain as variable, to proxy request to other site. Here is my nginx configuration

server {

    listen 80;
    server_name "~^(?<subdomain>.*).mydomain.com";

    location / {
            resolver 1.1.1.1 1.0.0.1 ipv6=off;
            proxy_pass http://hosting.mydomain.com/$subdomain/;
            proxy_redirect off;
            access_log /var/log/nginx/proxy.log;
    }

}

As I request the site directly and it loads perfectly

Site placed on AWS S3, and bucket static website address cnamed to mydomain

However, when I try to access via user1.mydomain.com, the page didn't load images, and css

This is the same site

And in browser network panel shows

Difference between direct and proxy access

This issue is made, because I have many sites stored in S3 bucket and located in different folders (the folder name is used as subdomain). And I want to use a single domain to access all of them via subdomains.

Thanks in advance


Solution

  • You forgot to proxy pass the URI, you're serving user1/index.html for every request, including for JS and CSS requests, it's why all of responses are the same size (2kb, the size of user1/index.html), and it's also why you're getting Uncaught SyntaxError: Unexpected token < in the first line of Enterprise_skeleton.bundle.js because it's returning an HTML document that starts with <!doctype html> instead of the actual JS bundle.

    Change

    location / {
      proxy_pass http://hosting.mydomain.com/$subdomain/;
    }
    

    to

    location / {
      proxy_pass http://hosting.mydomain.com/$subdomain$uri;
    }