server_redirect
The `server_redirect` directive allows dynamic redirection of incoming requests to specified servers based on configurable rules.
Description
The server_redirect directive in NGINX is used to redirect requests from one server to another based on defined conditions. This directive can accept one or two arguments; the first one is the target server name to which the request will be redirected, while the second one is an optional condition that can dictate when this redirection should take place, which can be useful for dynamic or conditional redirects based on request parameters or headers.
When configured, the directive processes incoming requests by evaluating the defined rules. Upon a match, it can redirect the request to the specified target server using internal mechanisms of NGINX. Also, the included schedule_redirect option can help control when the redirection occurs, providing additional flexibility for managing server traffic. This directive effectively allows for creating more adaptive and responsive server setups by redirecting traffic as needed without needing additional infrastructure changes.
The NGINX module then relies on several subroutines defined in its C code, managing how these rules are processed and triggering the applicable redirections based on the request's content and context. This can include handling variables that store the original requested host, allowing for more complex redirection scenarios that might depend on the origin of the request.
Config Example
http {
server {
listen 80;
server_name example.com;
# Redirect all requests to another server unconditionally.
server_redirect newserver.com;
location / {
proxy_pass http://newserver.com;
}
}
server {
listen 80;
server_name newserver.com;
# Retrieve the original host header in responses.
add_header x-original-host $server_redirect_original_host;
location / {
proxy_pass http://upstream.com;
}
}
}Ensure that the server names used are correctly defined in the NGINX configuration to avoid misdirection.
Conditional redirection must have proper variables defined beforehand; otherwise, the server will not redirect as expected.
Keep in mind that using this directive can cause an infinite redirect loop if misconfigured. Always test conditions carefully.