Examples
Adaptive Content Serving
Serving different content based on device type can improve user experience. This example demonstrates how to serve mobile-optimized pages without redirects.
location / {
set $variant "desktop";
if ($is_mobile) { set $variant "mobile"; }
if ($is_tablet) { set $variant "tablet"; }
proxy_pass http://backend;
proxy_set_header X-Device-Variant $variant;
}
if for setting variables is generally safe, but avoid complex logic inside location.
Cache Key Variation
Varying cache keys by device type ensures that users receive the appropriate content for their device. This example shows how to set cache keys based on device type.
# Vary cache by device type
proxy_cache_key "$scheme$request_uri|$device_type";
# Or just mobile vs desktop
proxy_cache_key "$scheme$request_uri|$is_mobile";
Bot Management
Blocking unwanted bots can protect resources and improve performance. This example blocks AI training crawlers from accessing content.
location / {
if ($is_ai_crawler) {
return 403 "AI crawlers not permitted";
}
}
if is acceptable here, avoid using it for directives that may lead to unexpected behavior.
Rate Limiting Scrapers
Rate limiting scrapers while allowing search engines can help manage traffic effectively. This example demonstrates how to implement rate limiting based on bot classification.
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
location / {
if ($is_bot) {
limit_req zone=one burst=5;
}
proxy_pass http://backend;
}
limit_req directive; it should not be placed inside an if block.
Debugging Device Information
Providing a debug endpoint can help in troubleshooting device detection issues. This example sets up a JSON endpoint to return device information.
location = /device {
default_type application/json;
return 200 $device_json;
}
See also
For more information on troubleshooting, see troubleshooting.md.