API Gateway Proxy URL Rewriting

Transform and route API requests dynamically with powerful URL rewriting rules. Implement pattern matching, regex substitutions, and intelligent path transformations to create flexible, maintainable API architectures.

Pattern Matching Regex Support Dynamic Substitution
Incoming Request
GET /api/v1/models/gpt-4 /completions
Rewrite Rule Applied MATCH
Pattern: /api/v1/models/{model}/*
Replace: /models/{model}/v1/*
Transformed URL
POST /models/gpt-4 /v1/completions

URL Rewriting Capabilities

Comprehensive tools for transforming API request paths in your gateway.

🎯

Pattern Matching

Define URL patterns with wildcards and placeholders to match incoming requests. Simple pattern syntax makes it easy to route requests based on path structure without complex regular expressions. Pattern variables capture path segments for use in rewritten URLs.

📝

Regular Expressions

Leverage full regex power for complex URL transformations when patterns aren't sufficient. Capture groups extract specific portions of URLs for conditional rewriting. Named groups make substitutions more readable and maintainable in production environments.

🔄

Dynamic Substitutions

Inject request context, headers, query parameters, and captured groups into rewritten URLs. Template variables support conditional logic and default values. Build destination URLs dynamically based on request characteristics and routing rules.

🔀

Conditional Routing

Apply different rewriting rules based on request method, headers, or other criteria. Route requests to different backend services conditionally. Implement A/B testing, canary deployments, and environment-specific routing through intelligent URL transformation.

Common Rewriting Rules

Practical URL rewriting patterns for API gateway configurations.

Version Migration Simple
From: /api/v1/* To: /api/v2/* Flags: redirect=301
Model Path Rewrite Template
From: /models/{model}/* To: /{model}/v1/* Example: /models/gpt-4/chat → /gpt-4/v1/chat
Query to Path Regex
Pattern: /search\?q=(.+) Replace: /search/$1 Example: /search?q=hello → /search/hello
Legacy Compatibility Simple
From: /completions To: /v1/completions Note: Maintain backward compatibility with old endpoint paths
Tenant Routing Template
From: /t/{tenant}/* To: /{tenant}/* Header: X-Tenant: {tenant} Auth: Validate tenant access
Region Routing Regex
Pattern: ^/(us|eu|asia)/(.*)$ Replace: /$2 Header: X-Region: $1 Route: Regional backends

Implementation Guide

Code examples for implementing URL rewriting in your gateway.

url_rewriter.py Python
# API Gateway URL Rewriting Engine import re from dataclasses import dataclass from typing import Optional, Dict, List from urllib.parse import urlparse, parse_qs @dataclass class RewriteRule: """URL rewriting rule configuration""" name: str pattern: str replacement: str is_regex: bool = False conditions: Optional[Dict] = None flags: Optional[Dict[str, any]] = None class URLRewriter: """URL rewriting engine for API gateway""" def __init__(self): self.rules: List[RewriteRule] = [] self.compiled_patterns: Dict[str, re.Pattern] = {} def add_rule(self, rule: RewriteRule): """Add rewriting rule to engine""" self.rules.append(rule) # Pre-compile regex patterns for performance if rule.is_regex: self.compiled_patterns[rule.name] = re.compile(rule.pattern) print(f"Added rewrite rule: {rule.name}") def rewrite( self, url: str, context: Optional[Dict] = None ) -> tuple[str, bool]: """Apply rewriting rules to URL""" context = context or {} parsed = urlparse(url) path = parsed.path for rule in self.rules: # Check conditions if not self._check_conditions(rule, context): continue if rule.is_regex: # Regex-based rewriting new_path, matched = self._apply_regex( rule, path, context ) else: # Pattern-based rewriting new_path, matched = self._apply_pattern( rule, path, context ) if matched: ## Reconstruct URL with new path new_url = self._reconstruct_url( parsed, new_path ) if rule.flags and rule.flags.get("last"): return new_url, True path = urlparse(new_url).path return url, False def _apply_pattern( self, rule: RewriteRule, path: str, context: Dict ) -> tuple[str, bool]: """Apply pattern-based rewriting""" # Extract variables from pattern pattern_parts = rule.pattern.split('/') path_parts = path.split('/') if len(pattern_parts) != len(path_parts): return path, False variables = {} for pp, up in zip(pattern_parts, path_parts): if pp.startswith('{') and pp.endswith('}'): var_name = pp[1:-1] variables[var_name] = up elif pp != up and pp != '*': return path, False # Substitute variables in replacement new_path = rule.replacement for var_name, var_value in variables.items(): new_path = new_path.replace( f"{{{var_name}}}", var_value ) return new_path, True def _apply_regex( self, rule: RewriteRule, path: str, context: Dict ) -> tuple[str, bool]: """Apply regex-based rewriting""" pattern = self.compiled_patterns[rule.name] match = pattern.match(path) if not match: return path, False # Apply substitution with captured groups new_path = pattern.sub(rule.replacement, path) return new_path, True def _check_conditions( self, rule: RewriteRule, context: Dict ) -> bool: """Check if rule conditions are met""" if not rule.conditions: return True for key, expected in rule.conditions.items(): actual = context.get(key) if actual != expected: return False return True def _reconstruct_url( self, parsed, new_path: str ) -> str: """Reconstruct URL with new path""" return parsed._replace(path=new_path).geturl() # Example usage rewriter = URLRewriter() # Add pattern-based rule rewriter.add_rule(RewriteRule( name="model_routing", pattern="/models/{model}/{endpoint}", replacement="/{model}/v1/{endpoint}", is_regex=False )) # Add regex-based rule rewriter.add_rule(RewriteRule( name="version_upgrade", pattern=r"^/api/v1/(.+)$", replacement=r"/api/v2/\1", is_regex=True, conditions={"method": "GET"} )) # Test rewriting original_url = "/models/gpt-4/completions" new_url, matched = rewriter.rewrite(original_url) print(f"{original_url} → {new_url}") # Output: /models/gpt-4/completions → /gpt-4/v1/completions

Partner Resources

Explore related gateway customization and transformation solutions.