Home > other >  How can I configure Nginx with dynamic third level domain and also port modification?
How can I configure Nginx with dynamic third level domain and also port modification?

Time:09-07

I have a website that is tenant based which uses the third level domain to determine the client. Some requests to this server map directly to folders for static files while others need to be remapped to a specific location while also maintaining their original subdomain structure so the API can determine which client is which. (probably doing a bad job of explaining so here are some examples)

http://www.example.com/css/whatever.css

http://www.example.com/js/whatever.js

The two urls above need to always go to the absolute path relative to the site root where the css and js files are stored

http://client1.example.com/api/myendpoint

This one should redirect to here: http://client1.example.com:8000/api/myendpoint

yet this one: http://client2.example.com/api/myendpoint

needs to go here: http://client2.example.com:8000/api/myendpoint

note, Front end is in React and backend is in Django if that matters.

Here is what I got so far but it's not working:

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /var/www/example;

  index index.html index.htm

  server_name example.com *.example.com;

  location /css/ {
    try_files $uri $uri/ =404;
  }
 
  location /js/ {
    try_files $uri $uri/ =404;
  }

  location /static/ {
    try_files $uri $uri/ =404;
  }

  location /api/ {
    proxy_pass http://example.com:8000;
  }

  location / {
    try_files /index.html =404;
  }
}

For clarification. My application allows clients to sign up on their own and when they do they get assigned a brand new third level domain which is whatever they decide it to be. So I need something that will forward whatever third level domain they choose to the correct version of it with the port added. aka

http://somethingrandom.example.com/api goes to http://somethingrandom.example.com:8000/api

Additionally, I have many many endpoints, they all start with the path /api so really what I need is this:

http://somethingrandom.example.com/api/v1/somerandomendpoint gets redirected to http://somethingrandom.example.com:8000/api/v1/somerandomendpoint

CodePudding user response:

For the part where you need to proxy something.example.com to something.example.com:8000, this should work:

location /api {
    proxy_pass http://$host:8000$request_uri;
}

I don't see any issues with your /css/, /js/ and /static/ rules. Please specify what kind of error you're while trying to access *.js or *.css URLs, if any.

  • Related