「NGINX-INGRESS-CONTROLLER」- 常见问题处理

配置 GeoIP 模块

How to block a country in Nginx ingress? : kubernetes

# 07/03/2022 我们暂时放弃通过 GeoIP 来实现安全访问控制,而采用其他方案。所以,我们这里仅简单记录配置思路,而具体配置可能存在错误;

NGINX Ingress Controller 支持 MaxMind GeoIP2 数据库,使用流程如下:

  1. 申请 MaxMind 的许可 | IP Geolocation and Online Fraud Prevention | MaxMind
  2. 调整 NGINX Ingress Controller 的配置,以使用许可 | NGINX Ingress Controller/ConfigMap/use-geoip2
  3. 通过 Annotation 进行相关配置:
...
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
      # server block
      map $geoip2_city_country_code $blocked_country {
        default 0;
        AU 1;
        FR 1;
      }
    nginx.ingress.kubernetes.io/configuration-snippet: |
      # location block
      if ($blocked_country) {
        return 403;
      }
...

场景 | 通过路径来区分服务

Kubernetes Cluster / Nginx Ingress Controller;
前端项目,静态页面,容器内 Nginx 提供访问;
通过路径 /web 来分流,以转发到对应的 Service 中;
页面静态资源使用相对路径,以保证静态资源请求能够进入后端容器;
同时,我们也不考虑修改代码。

通过 URL 重写

在 Container 中,站点需要放在根目录中。

在 Ingress 中,移除 /web 路径

… nginx.ingress.kubernetes.io/rewrite-target: /$2

… path: /web(/|$)(.*)

通过该方式,当 Ingress 请求 Service 时,将移除 /web 前缀。否则将返回 404 页面。

缺点:
1)需要访问 example.com/web/ 地址,如果使用 example.com/web 访问,则页面引用的静态资源无法正常访问。

通过 web 路径

在 Ingress 中,需要使用如下配置

… path: /web

… nginx.ingress.kubernetes.io/ssl-redirect: “true”

… nginx.ingress.kubernetes.io/preserve-trailing-slash: “true”

在 Container 中,站点需要存放在 /web/ 中,否则将返回 404 页面。

访问 example.com/web 将自动重定向到 example.com/web/ 地址 ⇒ 该行为与生成的 nginx.conf 及其 location 特性有关。

在 Container 中,其内 Nginx 行为导致该现象,
https://example.com/web 请求到达后端容器,后端容器 Nginx 因监听 HTTP 而将其重定向到
http://example.com/web/ 地址,而后 Ingress Nginx 再次重定向到
https://example.com/web/ 地址。

但是,在 Container 中的 Nginx 使用 HTTP 监听,所以我们暂时未找到方法来直接完成重定向。

preserve-trailing-slash: “true”,是另外的关键配置,否则
http://example.com/web/ 会被 Ingress Nginx 重定向为
https://example.com/web 地址,然后 后端容器 Nginx 又将其重定向为
http://example.com/web/ 地址,进而陷入循环。

ssl-redirect: “true”,该选项用于使得 preserve-trailing-slash: “true” 生效。