14

我有几个应用程序在 Nginx 反向代理后面运行,其中一个是带有 Express.js 的节点服务器。我正在代理domain.com/demo/app/<path>使用localhost:7003/<path>这个 Nginx 配置:

http {

    ...

    server {

        listen 80;
        server_name domain.com;

        ...

        location /demo/app {

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;

            rewrite ^/demo/app/?(.*) /$1 break;
            proxy_pass http://localhost:7003;
        }

        ...
    }
}

这很好用,并且app接收请求就好像它植根于/. 问题在于app处理它自己的静态文件,并且可能会请求路由,例如css/app.cssimages/image.jpg. 但是由于反向代理,这些实际上分别存在于/demo/app/css/app.css/demo/app/images/image.jpg

我通过让 Nginx 向 Node 传递一个自定义标头来解决这个问题,该标头指示根路径,Node 服务器将其添加到所有后续请求的 URL 之前。但是现在我的代码中到处都是这些根路径字符串。例如,我的部分后端模板:

link(rel='stylesheet', href="#{basePath}/css/base.css")
link(rel='stylesheet', href="#{basePath}/css/skeleton.css")
link(rel='stylesheet', href="#{basePath}/css/layout.css")

有什么更优雅的方式来处理这个问题?有没有办法让 Nginx 识别来自上游服务器的请求并自动将它们转发到该服务器?

4

1 回答 1

9

I have made nginx serve static files without even passing those requests to node by adding location directive to the app's nginx configuration file (which is included in nginx.conf):

location ~ /(img|js)/ {
    rewrite ^(.*)$ /public/$1 break;
}

location / {
    proxy_pass http://localhost:3000/;
    ...
}

In case request comes to /img or /js directory nginx serves files from /public/img or /public/js directory respectively. All other requests are proxied to node.

You can add more directories if you need (like /css or /views, if you store templates there that you want to use both in node and in browser) and have any directory structure inside those directories, nginx just prepends /public to them and gets files from there without your node app even knowing about it.

于 2012-12-26T14:02:02.987 回答