首页 > 解决方案 > 带有路径重写的 Nginx 代理配置

问题描述

我制作了一个与 nodeJS 服务器通信的 Angular 应用程序。我终于实现了使用以下配置文件配置 Angular 的开发 Web 服务器的代理,并且一切正常:

{  
    "/api/*": 
    {    
        "target": "http://localhost:8080",    
        "secure": false,    
        "pathRewrite": {"^/api" : ""}
    },
    "/sock/*": 
    {
        "target": "http://localhost:8060/socket.io/"
    }
}

然后我尝试使用 nginx Web 服务器部署我的应用程序,并使用以下配置配置服务器和代理:

server {
        listen 3600;
        listen [::]:3600;

        server_name localhost;

        root /home/ubuntu/mahe/tchernobyl/angular_tchernobyl/dist/tchernobyl;
        index index.html index.htm index.nginx-debian.html;

        location / {
                try_files $uri $uri/ /index.html;
        }

        location /sock {
                proxy_pass http://localhost:8060/socket.io;
        }

        location /api {
                   proxy_pass http://localhost:8080;
                   sub_filter /api/ /;
        }
}

不知何故,它最终似乎与 socket.io 一起工作,每次刷新时我只有一条错误消息,我不知道为什么:

WebSocket connection to 'ws://localhost:8100/sock/?EIO=3&transport=websocket&sid=qU-TS9vQwIPwZej7AAAK' failed: Error during WebSocket handshake: Unexpected response code: 400

编辑:通过应用此解决方案解决了这个非常次要的问题https://github.com/socketio/socket.io/issues/1942#issuecomment-82352072


但主要问题是,我完全可以通过 /api/[key] 访问我的快速服务器提供数据,但我无法获得任何数据。解释一下:我的快递服务器在 8080 上运行,网络在 3600 上运行。如果我输入http://localhost:8080/data,我会得到我的数据,但如果我输入http://localhost:3600/api/data我会得到“无法获取 /data”响应。(注意我用'sub_filter /api/ /;'重写)

我在控制台中收到以下消息:

Refused to execute a script because its hash, its nonce, or 'unsafe-inline' appears in neither the script-src directive nor the default-src directive of the Content Security Policy.

标签: node.jsangularnginxnginx-reverse-proxy

解决方案


这是“sub_filter /api/ /;” 没有像我想的那样重写 URL,我将其替换为

rewrite /foo/(.*) /$1 break;

它终于奏效了。

除了可以在最初编辑的消息中找到的调整之外:https ://github.com/socketio/socket.io/issues/1942#issuecomment-82352072


推荐阅读