Updated on 2024-11-12 GMT+08:00

Configuring URL Rewriting Rules for an Nginx Ingress

In some application scenarios, the access URL provided by the backend service is different from the path specified in the ingress rule. The ingress directly forwards the access path to the same backend path. If URL rewriting is not configured, 404 is returned for all access requests. For example, if the access path in the ingress rule is set to /app/demo and the access path provided by the backend service is /demo, access requests are directly forwarded to the /app/demo path of the backend service, which does not match the actual access path (/demo) provided by the backend service. As a result, 404 is returned.

In this case, you can use the Rewrite method to implement URL rewriting. That is, you can use the nginx.ingress.kubernetes.io/rewrite-target annotation to implement rewriting rules for different paths.

Configuring a Rewriting Rule

  1. Use kubectl to access the cluster. For details, see Connecting to a Cluster Using kubectl.
  2. Create a YAML file named ingress-test.yaml. The file name can be customized.

    vi ingress-test.yaml
    For clusters of v1.23 or later:
    apiVersion: networking.k8s.io/v1
    kind: Ingress 
    metadata: 
      name: ingress-test
      namespace: default
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /$2
    spec:
      rules:
        - host: ''
          http:
            paths:
              - path: '/something(/|$)(.*)'
                backend:
                  service:
                    name: <your_service_name>  # Replace it with the name of your target Service.
                    port:
                      number: <your_service_port>  # Replace it with the port number of your target Service.
                property:
                  ingress.beta.kubernetes.io/url-match-mode: STARTS_WITH
                pathType: ImplementationSpecific
      ingressClassName: nginx
    For clusters of v1.21 or earlier:
    apiVersion: networking.k8s.io/v1beta1
    kind: Ingress
    metadata:
      name: ingress-test
      namespace: default
      annotations:
        kubernetes.io/ingress.class: nginx
        nginx.ingress.kubernetes.io/rewrite-target: /$2
    spec:
      rules:
        - host: ''
          http:
            paths:
              - path: '/something(/|$)(.*)'
                backend:
                  serviceName: <your_service_name>  # Replace it with the name of your target Service.
                  servicePort: <your_service_port>  # Replace it with the port number of your target Service.

    As long as rewrite-target is specified for one ingress, all paths under the same host in all ingress definitions are case-sensitive, including the ingresses that do not have rewrite-target specified.

    In the preceding example, the placeholder $2 specifies that all characters matched by the second parenthesis (.*) are added to the nginx.ingress.kubernetes.io/rewrite-target annotation as the rewritten URL path.

    For example, the preceding regular expression matching for ingress causes URL rewriting in multiple cases. These cases include:
    • The /something path is rewritten to the / path.
    • The /something/ path is rewritten to the / path.
    • The /something/new path is rewritten to the /new path.

  3. Create an ingress.

    kubectl create -f ingress-test.yaml

    If information similar to the following is displayed, the ingress has been created:

    ingress/ingress-test created

  4. Check the created ingress.

    kubectl get ingress

    If information similar to the following is displayed, the ingress has been created:

    NAME          CLASS   HOSTS     ADDRESS          PORTS   AGE
    ingress-test  nginx   *         121.**.**.**     80      10s

  5. Access the ingress. ${ELB_IP} specifies the IP address of the load balancer associated with the Nginx ingress.

    curl ${ELB_IP}/something

    The access path will be redirected to /.

Checking the Configurations of an Ingress

In the nginx-ingress-controller container, you can check all configurations of an ingress in the nginx.conf file in the /etc/nginx directory.

  1. Obtain the name of the pod that runs nginx-ingress-controller.

    kubectl get pod -n kube-system | grep nginx-ingress-controller

    The command output is as follows:

    cceaddon-nginx-ingress-controller-66855ccb9b-52qcd        1/1     Running   0          37m

  2. Log in to the nginx-ingress-controller container.

    kubectl exec -it cceaddon-nginx-ingress-controller-66855ccb9b-52qcd -- /bin/bash

  3. Check the nginx.conf file in /etc/nginx.

    cat /etc/nginx/nginx.conf
    The rewriting rule in this example generates a Rewrite command and writes it to the location field in the nginx.conf file as follows:
    ## start server _
            server {
                    server_name _ ;
                    ...
                    location ~* "^/something(/|$)(.*)" {
                            set $namespace      "default";
                            set $ingress_name   "ingress-test";
                            set $service_name   "<your_service_name>";
                            set $service_port   "80";
                            ...
                            rewrite "(?i)/something(/|$)(.*)" /$2 break;
                            ...
                    }
            }
            ## end server _
    The basic syntax of the Rewrite command is as follows:
    rewrite regex replacement [flag];
    • regex: regular expression for matching URIs. In the preceding example, (?i)/something(/|$)(.*) is the regular expression for matching URIs, where (?i) indicates case-insensitive.
    • replacement: content to rewrite. In the preceding example, /$2 indicates that the path is rewritten to all the characters matched by the second parenthesis (.*).
    • flag: rewrite format.
      • last: continues to match the next rule after the current rule is matched.
      • break: stops matching after the current rule is matched.
      • redirect: returns a temporary redirect with the 302 code.
      • permanent: returns a permanent redirect with the 301 code.

Advanced Rewrite Configuration

Some complex, advanced Rewrite requirements can be implemented by modifying the Nginx configuration file nginx.conf. However, the nginx.ingress.kubernetes.io/rewrite-target annotation function can be customized to meet more complex Rewrite requirements.

  • nginx.ingress.kubernetes.io/server-snippet: Add custom settings to the server field in the nginx.conf file.
  • nginx.ingress.kubernetes.io/configuration-snippet: Add custom settings to the location field in the nginx.conf file.

Snippet is not enabled by default when the NGINX Ingress Controller version is 2.4.6 or later (corresponding to the community version v1.9.3). For details, see Changelog. If snippet is needed, enable it using allow-snippet-annotations.

You can use the preceding two annotations to insert a Rewrite command into the server or location field in the nginx.conf file to rewrite the URL. The following is an example:

annotations:
     kubernetes.io/ingress.class: "nginx"
     nginx.ingress.kubernetes.io/configuration-snippet: |
        rewrite ^/stylesheets/(.*)$ /something/stylesheets/$1 redirect;  # Add the /something prefix.
        rewrite ^/images/(.*)$ /something/images/$1 redirect;  # Add the /something prefix.
In the preceding rules, the /something prefix is added to the access URL. Specifically:
  • When a user accesses the /stylesheets/new.css path, the path is rewritten as the /something/stylesheets/new.css path.
  • When a user accesses the /images/new.jpg path, the path is rewritten as the /something/images/new.jpg path.