Nginx URL Redirection Best Practices: From Rewrite to Server Block Evolution

Nov 21, 2025 · Programming · 13 views · 7.8

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:

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:

Variable Usage Techniques

The configuration employs two important variables:

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:

  1. Use curl command for testing: curl -I http://test.com
  2. Check if the returned Location header is correct
  3. 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:

Extended Application Scenarios

This pattern can be extended to more redirection scenarios:

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.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.