$http_user_agent
The $http_user_agent variable contains the value of the User-Agent HTTP request header sent by the client. — NGINX Core (HTTP)
Description
The $http_user_agent variable in NGINX is used to capture the User-Agent string from incoming HTTP requests. This string identifies the client software making the request, which generally includes information about the client's browser type, version, and operating system. The User-Agent header is typically set by web browsers, mobile applications, and various user agents to inform the server about their capabilities and characteristics. It's important to note that this variable is populated in the request processing phase when the server receives the request, making it available for logging, processing, or conditional configuration. When the NGINX server processes an incoming request, it parses various HTTP headers, and among these headers is the User-Agent. If the User-Agent header is present in the request, its value is stored in the $http_user_agent variable, allowing server administrators to implement rules based on the type of client making the request. For example, administrators may choose to serve different content to different browsers or devices based on their User-Agent string. Typical values for this variable might include strings like "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" for Google Chrome or "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1" for Safari on iOS.
Config Example
server {
listen 80;
location / {
access_log /var/log/nginx/access.log;
if ($http_user_agent ~* "MSIE") {
return 403; # Deny access to Internet Explorer users
}
# other configuration...
}
}Subsystem
httpCacheable
YesContexts
http, server, location, ifEnsure that the User-Agent header is set in the request; otherwise, the variable will be empty.
Improper usage in conditional blocks can lead to unintended behavior if the User-Agent is not correctly parsed.
Be mindful of user-agent spoofing; clients can modify this header, making it unreliable for security decisions.