NGINX将带参数的/api路径请求全部重定向至子域名
Fixing Nginx Redirect for /api Paths to Subdomain
Let's break down what's wrong with your current configuration and get this redirect working exactly as you need it.
The Problem with Your Existing Setup
Your current rule:
location ~ /api(.*)$ { return 301 https://api.example.com/api/$request_uri$is_args$args; }
has two key issues causing broken redirects:
$request_urialready includes the full original path (including/apiand everything after it) plus any query parameters. Adding/api/before it creates duplicate path segments, which is why you're seeing mangled URLs likehttps://api.example.com//some_action.- You're combining
$request_uri(which already contains parameters) with$is_args$args, leading to redundant parameter strings that get dropped or mangled by Nginx.
Correct Configurations to Use
Option 1: Prefix Match (Recommended for Performance)
This is the simplest and most efficient way to handle all /api-prefixed requests:
server { listen 443 ssl; server_name example.com; # Redirect all /api requests to api subdomain, preserving full path and params location ^~ /api { return 301 https://api.example.com$request_uri; } # Your other main domain configurations (static files, other locations, etc.) }
^~ /apitells Nginx to use this prefix match before any regular expression locations, ensuring/apirequests are prioritized.$request_uricarries the entire original request path (e.g.,/api/some_action) and query parameters (e.g.,?params1=somevalue¶ms2=value2), so appending it directly tohttps://api.example.comgives you the exact URL structure you want.
Option 2: Regular Expression Match
If you prefer regex for more granular control, this works reliably too:
server { listen 443 ssl; server_name example.com; location ~ ^/api(.*)$ { return 301 https://api.example.com/api$1$is_args$args; } # Other main domain configs }
- The regex
^/api(.*)$captures everything after/apiinto the$1variable (e.g.,/some_actionfor/api/some_action). - We append
/api$1to reconstruct the original path, then add$is_args$argsto include any query parameters (safe here because$1doesn't include params).
Testing Tip
While debugging, use 302 Temporary Redirect instead of 301 Permanent Redirect—browsers cache 301s aggressively, which can make testing new configs frustrating. Once you confirm everything works as expected, switch back to 301.
Example Results
With either correct config, your test cases will behave exactly as needed:
https://example.com/api→https://api.example.com/apihttps://example.com/api/some_action→https://api.example.com/api/some_actionhttps://example.com/api/some_action?params1=somevalue¶ms2=value2→https://api.example.com/api/some_action?params1=somevalue¶ms2=value2
内容的提问来源于stack exchange,提问作者Ranknoodle
相关产品推荐
相关产品推荐

