You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
注册

Nginx Proxy Cache Key未保存查询参数变体问题求助

Fixing Nginx Proxy Cache Key for Specific Query Parameters

Hey there! I get it—your Nginx setup isn’t caching variations of your URLs that include id, toggle-on, and toggle-off query parameters, right? Let’s sort this out quickly.

The Root Cause

By default, Nginx uses $scheme$proxy_host$request_uri as the proxy_cache_key, which should include all query parameters. But if you’ve customized the cache key (or have unintended config that strips parameters), Nginx won’t distinguish between different values of your target parameters. The fix is explicitly including these parameters in your cache key (or adjusting your existing key to capture them properly).

Solutions

1. Explicitly Include Target Parameters in the Cache Key

If you only care about preserving variations of id, toggle-on, and toggle-off (and want to ignore other random query parameters), define a custom cache key that references these parameters directly:

# Add this inside your location / block
proxy_cache_key "$scheme$proxy_host$uri?$arg_id&$arg_toggle-on&$arg_toggle-off";
  • $arg_id captures the value of the id parameter (Nginx automatically maps query params to $arg_<param-name> variables, even with hyphens like toggle-on).
  • This ensures that any change to id (1-4 digits), toggle-on, or toggle-off will generate a unique cache entry.

2. Use a Clean, Parameter-Validated Cache Key (Advanced)

If you want to enforce that id is strictly a 1-4 digit integer (and ignore invalid IDs entirely), use a map directive to build a sanitized query string for your cache key. Add this to your http block first:

map $request_uri $sanitized_cache_query {
    # Match only valid id (1-4 digits) and optional toggle parameters
    ~*\?id=(\d{1,4})(?:&toggle-on=([^&]*))?(?:&toggle-off=([^&]*))? "$1&$2&$3";
    # Fallback for URLs without valid params (use empty string or default value)
    default "";
}

Then reference this mapped variable in your location’s cache key:

location / {
    proxy_cache_key "$scheme$proxy_host$uri?$sanitized_cache_query";
    # Your existing proxy config here...
}

This way, URLs with invalid id values (like id=abc or id=12345) will share a default cache entry, while valid parameter combinations get their own unique cache keys.

3. Revert to Default Cache Key (If You Want All Parameters)

If you want to cache all query parameter variations (not just the three you mentioned), use Nginx’s default cache key explicitly (in case you overwrote it earlier):

proxy_cache_key "$scheme$proxy_host$request_uri";

Post-Fix Steps

  1. Test your config for syntax errors with:
    nginx -t
    
  2. Reload Nginx to apply changes:
    nginx -s reload
    
  3. Test different URL variations (e.g., different id values or toggle-on strings) to confirm unique cache entries are being created.

内容的提问来源于stack exchange,提问作者Richard Kho

火山引擎 最新活动