如何阻止 NGINX 通过 URL 的标识部分发送?

How do I stop NGINX from sending through the identifying part of the URL?

我正在设置一个 AWS 实例来容纳我的 prometheus 和 grafana 服务器。我正在使用 NGINX 通过 /location 在两个客户端之间进行路由。问题是,NGINX 必须传递这个值,客户端无法理解它。

我的 NGINX 配置:

http {
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

sendfile            on;
tcp_nopush          on;
tcp_nodelay         on;
keepalive_timeout   65;
server_names_hash_bucket_size  128;
types_hash_max_size 4096;

include             /etc/nginx/mime.types;
default_type        application/octet-stream;

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

server {
    listen 80;
    listen [::]:80;
    server_name <aws instance url>;
    location /grafana {
            proxy_pass http://localhost:3000;
    }
    location /prometheus {
            allow <my ip>;
            deny all;
            proxy_pass http://localhost:9090;
    }
}

}

所以当我导航到 /grafana 时。它成功地把我带到了 grafana,但是 grafana 客户端试图解析 /grafana 并且找不到它的页面,并且 returns 一个 404.

有没有办法摆脱它,还是我的做法全错了?

是否需要保留 /grafana/prometheus 之后的其余 URI?

如果是,则需要重写URI:

server {
    ...
    location /grafana {
        rewrite ^/grafana(.*)$  break;
        proxy_pass http://localhost:3000;
    }
    location /prometheus {
        allow <my ip>;
        deny all;
        rewrite ^/prometheus(.*)$  break;
        proxy_pass http://localhost:9090;
    }
}

您可以参考 ngx_http_rewrite_module 上的 the documentation 以获取有关 rewrite 指令及其参数的更多信息。

如果没有,那么简单地说:

server {
    ...
    location /grafana {
        proxy_pass http://localhost:3000/; # Note the trailing slash here...
    }
    location /prometheus {
        allow <my ip>;
        deny all;
        proxy_pass http://localhost:9090/; # ...and here
    }
}

我在这两个只允许 prometheus 和 grafana 在子路径后面 运行 的解决方案之间找到了这个,所以 nginx 可以正常通过它:

对于 prometheus,在设置 --web.external-url=/prometheus/ 标志的情况下启动它: https://blog.cubieserver.de/2020/configure-prometheus-on-a-sub-path-behind-reverse-proxy/

对于 Grafana,在配置中设置 server.root_url: https://grafana.com/tutorials/run-grafana-behind-a-proxy/#1