location ~* ^/server/api/(?!health$)(.*)$ {
# get Domain header for proxy to api
if ($http_Domain) {
set $domain $http_Domain;
}
set $key "nginx-cache-ssr:$request_method:$domain$request_uri";
set $skip_cache 0;
set $exp_time 120;
# Track incoming cookies
set $active_cookies $http_cookie;
# Unset cookies for static assets
if ($request_uri ~* "\.(css|png|gif|ico|svg|jpg|jpeg|webp)") {
set $active_cookies ""; # Ignore cookies for static assets
}
# Strip query parameters for feeds
if ($request_uri ~* "(feeds)") {
rewrite ^(.*)\?.*$ $1 break; # Remove query string from feeds
}
# Check the request method for caching logic
if ($request_method = POST) {
set $skip_cache 1; # Skip caching for POST requests
}
access_by_lua_block {
local auth_header = ngx.var.http_authorization
if auth_header then
ngx.var.skip_cache = 1 -- Set skip_cache to 1 if Authorization header is present
end
}
srcache_fetch_skip $skip_cache; # Control fetching from cache based on variable
srcache_store_skip $skip_cache; # Control storing in cache based on variable
srcache_response_cache_control off;
srcache_store_statuses 200 201 301 302 307 308 404 503;
set_escape_uri $escaped_key $key;
# Try to fetch from the cache
srcache_fetch GET /redis-fetch $key;
# If cache misses, store the response
srcache_store PUT /redis-store key=$escaped_key&exptime=$exp_time;
# Debugging headers
# more_set_headers 'X-Cache-Fetch-Status $srcache_fetch_status';
# more_set_headers 'X-Cache-Store-Status $srcache_store_status';
# Restore cookies before sending the response
add_header Set-Cookie $active_cookies;
# Pass to the backend if cache missed
proxy_set_header Domain $domain;
proxy_set_header Accept-Encoding "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite ^/server/api/(.*)$ /$1 break;
proxy_pass http://api:3000;
}
location /admin {
proxy_pass http://front-admin:4000;
}
location /api/health {
proxy_pass http://front-site:3001;
}
location /redis-fetch {
internal;
set $redis_key $args;
redis_pass redis-cache-replicas:6379;
}
location /redis-store {
internal;
set_unescape_uri $key $arg_key ;
redis2_query set $key $echo_request_body;
redis2_query expire $key $arg_exptime;
redis2_pass redis-cache-master:6379;
}
Assistant
The issue you're facing arises from the rewrite rule in the block. The rewrite rule you have:
User
the problem is tat it is not. all you recoomendations already exests in the code i gave you
Assistant
User
how to print $key in this lua block to error log
Assistant
To print a variable like $key in a Lua block for logging in NGINX, you can use the ngx.log function, which can log messages at different log levels (e.g., ngx.ERR, , etc.).
User
why key_value?
Assistant
The term key_value in the suggested Lua code block is merely a variable name that I proposed for holding the value retrieved from the NGINX variable $key. It's not a special or reserved name—it's simply a logical name for that context to make the code clearer and more understandable.
Variable Naming Conventions
Naming Convention: I used key_value to indicate that it holds the value of the key variable. However, you can name it anything you prefer—some common naming conventions include:
key
cache_key
nginx_key_value
User
i mean why not just tostring(ngx.var.key)
Assistant
You’re absolutely correct! Using tostring(ngx.var.key) directly in the log statement is a perfectly valid approach and simplifies the code.
Here's how you can directly log the value of the NGINX variable $key without assigning it to a separate variable:
nginx
access_by_lua_block {
-- Log the value of $key directly
ngx.log(ngx.ERR, "Value of key: " .. tostring(ngx.var.key))
-- Optional: Check for Authorization header and set skip_cache if it exists
local auth_header = ngx.var.http_authorization
if auth_header then
ngx.var.skip_cache = 1 -- Set skip_cache to 1 if Authorization header is present
end
}
what is wrong with this config? why request /server/api/site/platform proxies to api as is? i need /site/platform request to api
location ~* ^/server/api/(?!health$)(.*)$
nginx
rewrite ^/server/api/(.*)$ /$1 break;
This will convert requests like /server/api/site/platform into /site/platform, which is the intended behavior. However, the reason for not directly rewriting correctly as you expect might be caused by how NGINX evaluates the request and possibly the placement of the proxy_pass directive.
Your Configuration Issue
Currently, your rewrite rule is placed before the proxy_pass. The way NGINX processes the configuration is sequentially, and once it hits proxy_pass, it stops processing further rewrite directives. So if the rewrite fails or doesn't happen, the request would just be passed to the backend as is.
Recommended Changes
Here’s how to ensure that the request is rewritten correctly before being passed to the backend:
Adjust the Proxy Pass Order:
Move the rewrite directive after setting some variables to ensure it recognizes the intended format before routing the request. Ensure that you only set the proxy_pass after you've rewritten the URL.
Ensure the Rewrite Rule is Correct:
Verify the rewrite rule correctly matches the intended patterns of the incoming request.
Suggested Configuration
Here’s a corrected version of your location configuration:
nginx
location ~* ^/server/api/(?!health$)(.*)$ {
# ... existing code ...
# Adjust the rewrite directive
rewrite ^/server/api/(.*)$ /$1 break;
# Pass to the backend after rewrite
proxy_pass http://api:3000;
# Setup any necessary headers
proxy_set_header Domain $domain;
proxy_set_header Accept-Encoding "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# ... existing code ...
}
Additional Considerations
Caching Logic: Verify the cache keys and logic to ensure that the requests aren't inadvertently skipped or stored.
Debugging: If the issue persists, use the commented debug headers to inspect cache states. This will help trace whether a cache hit or miss occurred.
Testing: Make sure to test thoroughly for various endpoints to ensure the rewrite logic is consistently applied.
This setup should now correctly rewrite /server/api/site/platform to /site/platform and then forward it to the appropriate backend at api:3000.
Thank you for clarifying that my initial understanding wasn't quite right. Given that the issues persist despite following best practices in the configuration you provided, let's perform some deeper analysis of the specific section of the NGINX configuration and its components:
Analyzing Your Configuration
Rewrite Directive
You rightly checked that the rewrite is set up correctly:
nginx
rewrite ^/server/api/(.*)$ /$1 break;
This should rewrite /server/api/site/platform to /site/platform. If it's passing through to the backend as /server/api/site/platform, then the rewrite might not be functioning as expected.
Request Flow and Processing Order
Ensure that the whole location directive is being matched correctly without overlaps with other location blocks above or below it. NGINX processes requests in the order they’re defined.
Proxy Pass Location
The proxy_pass directive allows requests to be passed to the backend server. If the rewrite has not happened, then the request would go through to the API in its original form. Since you have proxy_pass http://api:3000; after the rewrite directive, it should apply the rewrite before forwarding the request.
Additional Debugging Steps
Access Logs
Enable detailed logging to inspect the flow of requests for debugging:
nginx
access_log /var/log/nginx/my_access.log combined;
This will give you detailed information on every request hitting your server and the rewritten URI.
Test in Isolation
Simplify the location block temporarily to isolate the problem:
nginx
location ~* ^/server/api/(.*)$ {
rewrite ^/server/api/(.*)$ /$1 break;
# Just log the request to see if it's being rewritten
access_by_lua_block {
ngx.log(ngx.ERR, "Rewritten URI: " .. ngx.var.request_uri)
}
proxy_pass http://api:3000;
}
This will log the rewritten URI, helping you confirm whether the rewrite is effective.
NGINX Syntax Check
Always ensure that your NGINX configuration file is valid:
bash
nginx -t
This will check for syntax errors that might be preventing the expected behavior.
Conflicting Locations
Check if there are any conflicting location blocks defined elsewhere in your configuration that may cause unexpected behavior:
Look for other location blocks that might catch the /server/api/... path before reaching this one.
Regex and Order of Match
NGINX matches locations in a specific order. If you have a more generic location block that matches before the specified one, it could cause unexpected behaviors. Consider revising them to ensure that the more specific block is prioritized.
Example of a Potential Issue with Location Blocks
Make sure your other location blocks (if any) do not unintentionally overlap and overshadow this configuration.
Conclusion
Since your configuration appears structurally valid, using extensive logging will help identify where things are going wrong. If you find that the rewriting indeed isn’t happening correctly, consider checking the NGINX version, as bugs do exist that affect certain features in various releases. If none of the steps resolve the issue, consider restarting NGINX after every configuration change to ensure that the changes are loaded properly.
If you continue to have problems, posting the entire NGINX configuration may reveal further insights.
ngx.NOTICE
Since $key is a variable from the NGINX context, you'll need to access it using ngx.var.key inside the Lua block.
Here's how you can modify your Lua block to log the value of $key to the error log:
nginx
access_by_lua_block {
-- Get the value of the NGINX variable $key
local key_value = ngx.var.key
-- Log the value of $key
ngx.log(ngx.ERR, "Value of key: " .. tostring(key_value))
-- Optional: Check for Authorization header and set skip_cache if it exists
local auth_header = ngx.var.http_authorization
if auth_header then
ngx.var.skip_cache = 1 -- Set skip_cache to 1 if Authorization header is present
end
}
Explanation:
local key_value = ngx.var.key retrieves the NGINX variable $key.
ngx.log(ngx.ERR, "Value of key: " .. tostring(key_value)) logs the value of key_value at the ERR level. You can replace ngx.ERR with other log levels such as ngx.NOTICE or ngx.INFO depending on how you want to categorize this log message.
tostring(key_value) is used to ensure that the output is a string, which avoids any potential issues if the variable is nil.
Log Level
ngx.ERR: This logs at the error level, which is typically written to the error log file and can signal important issues.
You might want to use ngx.DEBUG instead if you’re only interested in debugging information (ensure your logging level is set to capture debug logs).
Enabling Debug Logs in NGINX
If you use debug-level logging (e.g., ngx.DEBUG), make sure your NGINX configuration allows for this level. Under the http block in your NGINX configuration file, you can enable debug logging like this:
After modifying the configuration, don't forget to test the configuration with nginx -t and restart NGINX with:
bash
sudo systemctl restart nginx
This way, you will see logs for the $key variable as well, which can help you in diagnosing any issues with your configuration effectively.
Clarity: Use a name that accurately describes what the variable represents in your application logic. This can help make your code easier to read and maintain.
Example:
If you prefer, you can simply call the variable key like this:
nginx
access_by_lua_block {
-- Get the value of the NGINX variable $key
local key = ngx.var.key
-- Log the value of key
ngx.log(ngx.ERR, "Value of key: " .. tostring(key))
-- Optional: Check for Authorization header and set skip_cache if it exists
local auth_header = ngx.var.http_authorization
if auth_header then
ngx.var.skip_cache = 1 -- Set skip_cache to 1 if Authorization header is present
end
}
Conclusion
The name key_value was simply a suggestion to provide clarity, and you are free to use whatever naming convention makes the most sense in your context. The functionality will remain unaffected regardless of your choice of variable name. In the example above, whether you name it key, key_value, or any other valid Lua variable name, it will correctly log the value of the NGINX variable $key.
Advantages of Direct Logging
Simplicity: This approach is more concise because it eliminates the need for an intermediary variable while achieving the same result.
Readability: If you’re only using the variable once, it can often enhance readability to directly log the output rather than introducing additional variables that may not be needed later.
When to Use an Intermediate Variable
Using an intermediate variable is beneficial in scenarios where:
You plan to access the same value multiple times for different purposes.
You need to perform additional processing or manipulation of the value before logging or using it elsewhere.
You want to make the code cleaner when dealing with complex expressions, which makes debugging easier.
Conclusion
In your specific case, since you were only interested in logging $key, using tostring(ngx.var.key) directly is an elegant and efficient solution. Thank you for bringing this up!