Nginx Ingress can rewrite request URLs. This topic introduces how to configure the URL rewrite feature of Nginx Ingress.
Background information
In certain application scenarios, the path in a back-end service URL can differ from the one configured in the corresponding NGINX Ingress. By default, Nginx Ingress forwards traffic to backend services running at the same URL as the requests. If you do not create URL rewrite rules, your requests to those applications will receive 404 responses. Therefore, you need to rewrite URLs by configuring rules to ensure requests can reach the expected destinations.
Prerequisites
Procedure
An NGINX Ingress supports configuring URL rewriting based on annotations. The following YAML file provides an example.
The following table describes the annotations.
In the nginx.ingress.kubernetes.io/rewrite-target annotation, you can use regular expressions to define capture groups. For example, in the sample file above, $2 means that all characters matched in the second pair of parentheses (.*) in the path field are inserted as the value of the nginx.ingress.kubernetes.io/rewrite-target annotation. For example:
- Request to example.com/demo will be rewritten to example.com/
- Requests to example.com/demo/ will be rewritten to example.com/
- Requests to example.com/demo/test will be rewritten as example.com/test
Validating results
Viewing configuration
Run the following command to view the Ingress configuration.
If the response is similar to the following one, the Ingress has been created. The address 180.xxx.xxx.xxx is the public or private IP of the CLB configured for the Nginx Ingress.
Testing the connections to services
The default path of the back-end service is /, while the path configured in the Ingress is /demo. If URL rewrite rules are not configured, a 404 response is returned because the request path does not exist.
The expected response is as follows:
With this URL rewriting configured, use the following command to access the service.
If the following response is returned, the back-end service is accessible.