server_name_in_redirect
The server_name_in_redirect directive controls whether the server name is included in redirects.
Description
The server_name_in_redirect directive, when enabled, modifies the behavior of NGINX when producing redirects (e.g., HTTP 301 or 302 responses) for requests handled by the server. Specifically, it determines whether the redirect URLs will include the server_name specified in the server block configuration. By default, when a redirect occurs, NGINX may use the Host header from the request to construct the redirect URL, but enabling this directive forces NGINX to use the server_name instead.
This directive can be particularly useful in cases where the NGINX server is serving multiple domain names (i.e., virtual hosts) and you want to ensure that the redirects always reflect one specific domain. For example, if a request comes in for example.com, but you're configured to redirect to www.example.com, setting server_name_in_redirect to on ensures that all redirects consistently use www.example.com. The directive accepts a flag, where the value can be on to enable the behavior or off to disable it, allowing for easy and flexible configuration in different contexts such as http, server, and location blocks.
Config Example
server {
listen 80;
server_name example.com www.example.com;
server_name_in_redirect on;
location / {
return 301 https://www.example.com$request_uri;
}
}Forgetting to set this directive in the appropriate context can lead to inconsistent redirect behavior.
If using multiple server blocks, ensure each has the correct server_name set to avoid unexpected results.