$scheme
The $scheme variable in NGINX returns the protocol of the current request (HTTP or HTTPS). — NGINX Core (HTTP)
Description
The $scheme variable is essential for determining the protocol used by the client to initiate a request to the server. It checks if the connection to the NGINX server was made using HTTPS or HTTP. When the request is made over HTTPS, the $scheme variable will return 'https', while for HTTP requests, it will return 'http'. This variable is typically set during the processing of a request in the NGINX core, and its value is determined by the presence or absence of a valid SSL certificate on the server. Therefore, if SSL is configured and the request is secured, the variable is set to 'https'. Otherwise, it defaults to 'http'. It's also important to note that scripts, redirects, or other configuration options often use this variable to generate correct URLs in response outputs or HTTP headers. For example, when redirecting a user or building links dynamically, using the $scheme variable ensures that links reference the appropriate protocol based on how the user accessed the server. Therefore, it plays a crucial role in environments where both secure and non-secure access can exist simultaneously.
Config Example
server {
listen 80;
server_name example.com;
location / {
return 301 $scheme://www.example.com$request_uri;
}
}Subsystem
httpCacheable
YesContexts
http, server, location, ifEnsure SSL is configured properly; otherwise, it will always return 'http'.
Avoid using $scheme in contexts where it may not be defined, such as inside certain directives that do not handle requests.
Using $scheme too liberally can lead to security issues if not handled correctly, such as exposing internal endpoints over HTTP.