node.js - 如何在三个 Node 应用程序前使用 NGINX 管理相对 CSS 路径

标签 node.js nginx

我们尝试在 NGINX 后面代理几个 Node 应用程序。这些 Node 应用程序中的每一个都是独立开发的,html 中的所有相对路径都指向/的文档根目录。

有没有办法让 nginx 帮助提供这些静态 CSS/JS 文件?

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>

可以看到,app1的index.html指向了一个“/stylesheets/style.css”的相对路径。 Nginx 把这个放在后面 http://localhost:8180/app1 , 因此一旦将 html 提供给客户端,该路径就不会被识别。

我意识到我可以更改所有三个应用程序中的 html 以使用映射到 css 的完整路径,例如:http://localhost:8180/app1/stylesheets/styles.css .

我很好奇是否有人对此有任何建议。在为多个应用程序提供服务时,处理此类问题的正确方法是什么?

最佳答案

我遇到了类似的问题并发现了这个 reddit thread .我有一个 Node express 应用程序。通过删除 href 值中的前导斜杠(相对路径而不是绝对路径),它能够构建正确的路径。 nginx 中的位置设置:

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

<link rel="stylesheet" href="/css/theme.css">浏览器会尝试加载 mydomain.com/css/theme.css并失败(错误的路径,什么都没有),但是 <link rel="stylesheet" href="css/theme.css">浏览器将成功加载 mydomain.com/app1/css/theme.css

关于node.js - 如何在三个 Node 应用程序前使用 NGINX 管理相对 CSS 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25328875/

相关文章:

node.js - 致命: Invalid refspec (Heroku nodejs)

node.js - 在管道内调用函数,在 gulp 中返回什么?

php - RESTful API 的 nginx 配置

linux - Nginx url重写错误: [emerg] unexpected "}"

docker - Nginx在docker-compose中挂起 “http://localhost”

java - Tomcat 处理时间很小但 nginx 显示它很大

node.js - 将新的 Mongoose 中间件前提条件应用于集合中所有现有的元素

node.js - 使用预设时是否可以选择禁用 babel 中的插件?

javascript - Gulp - 导致任务停止的错误

Nginx 配置未针对浏览器更新