AWS ALB Ingress Controller如何实现URL重写?Nginx注解无效怎么办?
Absolutely! While the nginx.ingress.kubernetes.io/rewrite-target annotation doesn’t work with AWS ALB Ingress (it’s specific to the NGINX Ingress Controller), the AWS ALB Ingress Controller does support URL rewriting—it just uses a different configuration pattern tailored to AWS Application Load Balancer’s native capabilities.
How to Set Up URL Rewriting in AWS ALB Ingress
Instead of a single annotation, ALB Ingress uses custom action configurations to define rewrite rules. Here’s a practical breakdown with an example:
1. Define a Rewrite Action via Annotation
Add an annotation to your Ingress resource that specifies the rewrite rule using JSON syntax. This lets you define the path pattern to match and the replacement path.
2. Reference the Action in Your Path
Instead of pointing directly to a service in your path’s backend, you’ll reference the rewrite action you defined.
Full Example Configuration
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: my-alb-ingress annotations: # Basic ALB setup alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip # Define the rewrite rule action alb.ingress.kubernetes.io/actions.rewrite-to-root: | { "Type": "rewrite", "RewriteConfig": { "Path": { "Pattern": "^/app/(.*)", "ReplaceWith": "/$1" } } } spec: ingressClassName: alb # Ensure you're using the ALB Ingress class rules: - http: paths: # Path that triggers the rewrite - path: /app/* pathType: ImplementationSpecific backend: service: name: rewrite-to-root # Match the action name from the annotation port: name: use-annotation # Required fixed port name for actions # Direct path to a service without rewrite - path: /static pathType: ImplementationSpecific backend: service: name: my-static-service port: number: 80
Key Details to Note
- Action Naming: The annotation key follows
alb.ingress.kubernetes.io/actions.<action-name>—replace<action-name>with a descriptive label for your rule. - Regex Syntax: The pattern uses AWS ALB-compatible regex. Basic features like capturing groups
(.*)work the same as NGINX, but avoid advanced features like lookaheads/lookbehinds that ALB doesn’t support. - Port Name: When referencing an action in the backend, the port name must be
use-annotation—this tells the controller to use the annotated action instead of a real service port. - Validation: After deployment, verify the rule by checking your ALB’s listener rules in the AWS Console, or test with
curl:curl https://your-alb-domain.com/app/test-path # This should route to your service at /test-path
Multiple Rewrite Rules
For multiple patterns, define additional actions with unique names and reference them in separate paths:
# Add another rewrite action alb.ingress.kubernetes.io/actions.rewrite-to-api: | { "Type": "rewrite", "RewriteConfig": { "Path": { "Pattern": "^/api/v1/(.*)", "ReplaceWith": "/v2/$1" } } }
内容的提问来源于stack exchange,提问作者Martin Tovmassian

