Nginx入口控制器-基于路径的路由

时间:2020-07-24 21:37:41

标签: nginx kubernetes google-kubernetes-engine kubernetes-ingress nginx-ingress

我正在运行Nginx入口控制器,并希望只允许用户连接和休息所有我想阻止或提供403错误的路径。我该怎么办?

我只希望用户允许连接/example,其余所有都应被阻止。

kind: Ingress
metadata:
  name: ingress1
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: ingress.example.com
    http:
      paths:
      - path: /example
        backend:
          serviceName: ingress-svc
          servicePort: 80

我可以添加一个Nginx服务器代码段吗?

     location path {
       "if the path is not matching then deny"
       deny all;
     }```

2 个答案:

答案 0 :(得分:1)

在下方使用自定义后端

apiVersion: apps/v1
kind: Deployment
metadata:
  name: custom-http-backend
spec:
  selector:
    matchLabels:
      app: custom-http-backend
  template:
    metadata:
      labels:
        app: custom-http-backend
    spec:
      containers:
      - name: custom-http-backend
        image: inanimate/echo-server
        ports:
        - name: http
          containerPort: 8080
        imagePullPolicy: IfNotPresent
---
apiVersion: v1
kind: Service
metadata:
  name: custom-http-backend
spec:
  selector:
    app: custom-http-backend
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

然后在您的入口添加此规则

- host: ingress.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: custom-http-backend
          servicePort: 80

答案 1 :(得分:0)

除了@Tarun Khosla提到的是正确的内容外,还有另一个stackoverflow question及其示例可能会有所帮助。我将其发布为社区Wiki答案,以提高社区的知名度,请随时进行扩展。

@Nick Rak提供了2个示例


我遇到了同样的问题,并在github上找到了解决方案。 为了实现您的目标,您需要默认情况下首先创建两个Ingress,没有任何限制:

apiVersion: extensions/v1beta1
 kind: Ingress
 metadata:
 name: ingress-test
 spec:
   rules:
   - host: host.host.com
   http:
      paths:
        - path: /service-mapping
      backend:
         serviceName: /service-mapping
         servicePort: 9042

然后,按照doc中的说明为身份验证创建secret

创建htpasswd

$ htpasswd -c auth foo
New password: <bar>
New password:
Re-type new password:
Adding password for user foo

创建secret

$ kubectl create secret generic basic-auth --from-file=auth
secret "basic-auth" created

具有auth的第二个入口,用于您需要限制的路径:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-with-auth
  annotations:
    # type of authentication
    nginx.ingress.kubernetes.io/auth-type: basic
    # name of the secret that contains the user/password definitions
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    # message to display with an appropiate context why the authentication is required
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required - foo"
spec:
  rules:
  - host: host.host.com
    http:
      paths:
      - path: /admin
        backend:
          serviceName: service_name
          servicePort: 80

根据sedooe answer,他的解决方案可能存在一些问题。


和@sedooe

您可以使用server-snippet注释。 This似乎正是您想要实现的目标。