Keywords: Nginx Redirection | Server Block | URL Rewriting
Abstract: This article provides an in-depth exploration of URL redirection implementation in Nginx, comparing the advantages and disadvantages of Rewrite directives versus Server Block solutions. It thoroughly explains the causes of redirection loop issues and their resolutions, based on practical case studies. The paper systematically elaborates on proper configuration of 301 permanent redirects, covering key technical aspects including server_name matching rules, $scheme variable usage, and request URI preservation, with complete configuration examples and performance optimization recommendations.
Introduction
URL redirection is a common requirement in web server configuration, particularly for domain standardization and website migration scenarios. Nginx, as a high-performance web server, offers multiple approaches to implement redirection, but different methods exhibit significant variations in correctness, performance, and maintainability.
Problem Analysis: Causes of Redirection Loops
In the original configuration, the developer attempted to use rewrite ^/(.*) http://www.test.com/$1 permanent; directive to achieve redirection from test.com to www.test.com. However, this configuration resulted in redirection loop errors, with browsers reporting "The page isn't redirecting properly".
The root cause lies in the overly broad matching scope of the rewrite rule. When requests reach www.test.com, this rule might still be triggered, causing infinite redirection loops. Specifically:
- The original configuration was defined only in the server block with
server_name test.com rewrite ^/(.*)matches all paths starting with a slash- Redirected requests might match the same rule again
Solution: Server Block-Based Redirection Architecture
The best practice involves using dedicated server blocks specifically for handling redirection logic:
server {
server_name test.com;
return 301 $scheme://www.test.com$request_uri;
}Concurrently, modify the main server block configuration:
server_name www.test.com;In-Depth Technical Principles
Server Block Matching Mechanism
Nginx selects the appropriate server block to process requests based on the value of the server_name directive. When accessing test.com, Nginx preferentially matches the block with server_name test.com, executing a 301 redirect to www.test.com. Subsequently, the request is normally processed by the block with server_name www.test.com.
Advantages of Return Directive
Compared to the rewrite directive, the return directive offers the following advantages:
- Better Performance:
returndirectly returns responses without involving regex matching and rewriting processes - Clear Semantics: Explicitly specifies HTTP status codes and redirect targets
- Avoids Pitfalls: Eliminates potential loops and edge conditions that rewrite rules might cause
Variable Usage Techniques
The configuration employs two important variables:
$scheme: Automatically captures the request protocol (http or https), ensuring protocol consistency after redirection$request_uri: Contains the complete URI of the original request (including query parameters), preventing path information loss
Configuration Examples and Verification
The complete configuration file structure is as follows:
# Redirection server block
server {
listen 80;
server_name test.com;
return 301 $scheme://www.test.com$request_uri;
}
# Main server block
server {
listen 80;
server_name www.test.com;
client_max_body_size 10M;
client_body_buffer_size 128k;
root /home/test/test/public;
passenger_enabled on;
rails_env production;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}Verification methods:
- Use curl command for testing:
curl -I http://test.com - Check if the returned Location header is correct
- Confirm HTTP status code is 301
Related Technology Comparison
Differences Between Rewrite and Return
The referenced article case demonstrates the limitations of rewrite directive in path handling. When attempting to redirect http://example.com/something to http://answares.com/examples_com/something, improper rewrite rules might cause double slash issues or path truncation.
Writing like rewrite ^(.*) http://answares.com/examples_com$1 permanent; easily produces abnormal URLs such as http://answares.com/examples_com//something.
Avoidance of If Directive
Nginx official documentation explicitly recommends avoiding the use of if directive in location contexts, as its behavior during rewrite phases might produce unexpected results. "if is evil" has become a classic warning in Nginx configuration.
Performance Optimization Considerations
The Server Block-based redirection solution demonstrates clear performance advantages:
- Reduced Regex Matching: Avoids expensive regular expression computations
- Early Termination: Completes redirection at the earliest stage of request processing
- Cache Friendly: 301 redirects can be cached by browsers and CDNs
Extended Application Scenarios
This pattern can be extended to more redirection scenarios:
- HTTP to HTTPS redirection
- Old domain to new domain migration
- Multiple subdomain standardization
- Geographic redirection configuration
Conclusion
URL redirection in Nginx should prioritize Server Block-based architecture, implemented using the return directive. This approach not only resolves redirection loop issues but also provides better performance, maintainability, and scalability. Developers should deeply understand Nginx's request processing flow and configuration best practices, avoiding potentially risky rewrite and if directives.