首页 > 解决方案 > 我可以在 Nginx 中创建一个“私人”位置吗?

问题描述

我可以创建一个可以被 nginx 配置中的任何其他位置访问并且不能从外部直接访问的位置吗?

我可以使用拒绝指令,但它也会拒绝访问 nginx 配置中定义的位置。

这是我的配置 -

server {
  listen *:80;
  server_name 127.0.0.1;

  location = /auth {
      set $query '';
      if ($request_uri ~* "[^\?]+\?(.*)$") {
         set $query $1;
      }
      # add_header X-debug-message "Parameters being passed $is_args$args" always;
      proxy_pass http://127.0.0.1:8080/auth?$query;
  }

  location /kibana/ {
     rewrite ^/kibana/(.*) /$1 break;
     proxy_pass http://127.0.0.1:5601;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection 'upgrade';
     proxy_set_header Host $host;
     proxy_set_header X-Forwarded-For $remote_addr;
     proxy_set_header  X-Real-IP  $remote_addr;
     proxy_cache_bypass $http_upgrade;
     auth_request /auth;
  }

  location ~ (/app/|/app/kibana|/bundles/|/kibana4|/status|/plugins|/ui/|/api/|/monitoring/|/elasticsearch/) {
     internal;
     proxy_pass http://127.0.0.1:5601;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
     proxy_set_header Host $host;
     rewrite /kibana4/(.*)$ /$1 break;
  }

  error_page 404 /404.html;
    location = /40x.html {
  }

  error_page 500 502 503 504 /50x.html;
    location = /50x.html {
  }
}

所以,我需要最后一个位置才能从位置 /kibana/ 访问,但internal;它会抛出 404 错误,没有它可以正常工作。

我实际上需要用 nginx 保护 kibana,但无论如何我最终会在没有任何身份验证的情况下有效地暴露它。

标签: nginxnginx-locationnginx-configauth-request

解决方案


您可以使用一种叫做命名位置的东西。它根本无法从外部访问,但在您的配置中,您可以在某些情况下引用它:

location @nginxonly {
    proxy_pass http://example.com/$uri$is_args$args;
}

创建命名位置后,您可以在其他一些try_files地方引用它,例如指令中的最后一项。


推荐阅读