Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manage relative CSS paths with NGINX in front of three node apps

Tags:

node.js

nginx

We have several node applications that we are trying to proxy behind NGINX. Each of these node application has been developed standalone with all relative paths in the html pointing to document root of /.

Is there a way to get nginx to help serve up these static CSS / JS files?

nginx.conf

worker_processes  1;

events {
    worker_connections  1024;
}


http {

    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    upstream app1 {
        server localhost:3001;
    }

    upstream app2 {
        server localhost:3002;
    }

    upstream app3 {
        server localhost:3003;
    }

    server {
        listen       8180;
        server_name  localhost;

        location /app1 {
            proxy_pass http://app1/;
        }

        location /app2 {
            proxy_pass http://app2/;
        }

        location /app3 {
            proxy_pass http://app3/;
        }
   }
}

app1 index.html

   <html>
    <head>
     <title>Express</title>
     <link rel="stylesheet" href="/stylesheets/style.css">
    </head>
    <body>
      <h1>Express</h1>
      <p>Welcome to Express</p>
      <p class="foo">A simple test to see if the app is served correctly</p>
    </body>
  </html>

As you can see, the index.html of app1 points to a relative path of "/stylesheets/style.css". Nginx puts this behind http://localhost:8180/app1, so that path does not get recognized once the html is served to the client.

I realize that I could change the html in all three applications to use full paths that map to css like: http://localhost:8180/app1/stylesheets/styles.css.

I'm just curious if anyone has any advice on this. What is the right way to handle this type of problem when serving up multiple applications?

like image 789
Jason Avatar asked Nov 10 '22 03:11

Jason


1 Answers

I was having a similar issue and found this reddit thread. I have a node express app. By removing the leading slash in the href value (relative-path instead of absolute-path), it was able to build the correct path. The location settings in nginx:

location /app1/ {
   proxy_pass http://localhost:3002/;
   alias /app1/client;
}

and with <link rel="stylesheet" href="/css/theme.css"> the browser would try to load mydomain.com/css/theme.css and fail (wrong path, nothing there), but with <link rel="stylesheet" href="css/theme.css"> the browser would successfully load mydomain.com/app1/css/theme.css

like image 114
danbjoseph Avatar answered Nov 14 '22 23:11

danbjoseph