search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
NGINX URL Redirect Basics
Understanding the rewrite command
Practical example: Redirect root path to URL with query parameters
Configuration details
301 permanent redirect vs. 302 temporary redirect
Things to note and best practices
Summarize
Home Backend Development PHP Tutorial NGINX URL redirection in action: detailed explanation and best practices

NGINX URL redirection in action: detailed explanation and best practices

Apr 22, 2026 am 06:17 AM

NGINX URL redirection in action: detailed explanation and best practices

This article aims to provide a professional tutorial on how to configure URL redirection using Nginx. We will focus on the use of the rewrite directive, especially how to redirect the root path to a URL with query parameters, and delve into the difference between the redirect (302 temporary redirect) and permanent (301 permanent redirect) flags and their considerations in SEO and browser caching to ensure that the Nginx configuration is both efficient and in line with best practices.

NGINX URL Redirect Basics

URL redirection is a common and important task in web service management, which allows us to forward old or specific URL requests to a new URL. This is critical for scenarios such as site migration, URL structure optimization, forcing the use of HTTPS, or adding specific query parameters as described in this article. Nginx provides a powerful rewrite command to achieve this function.

Understanding the rewrite command

The rewrite directive is the core tool in Nginx for URL rewriting and redirection. Its basic syntax is as follows:

 rewrite regex replacement [flag];
  • regex : A regular expression used to match the request URI. When the requested URI matches this regular expression, the rewrite operation will be performed.
  • replacement : the rewritten target URI. This can be a new path, file, or full URL with query parameters.
  • flag : A flag that controls overriding behavior. This is the key to successful redirection. Commonly used signs include:
    • last : After completing the current rewrite rule, stop processing other rewrite rules in the current location block, and then Nginx will re-find the matching location block based on the rewritten URI.
    • break : After completing the current rewrite rule, stop processing other rewrite rules in the current location block and no longer search for the location block again. The request will be processed within the current location block.
    • redirect : Returns an HTTP 302 temporary redirect response. The client browser will receive this response and initiate a new request based on the URL in the replacement.
    • permanent : Returns an HTTP 301 permanent redirect response. This indicates to clients (including search engine crawlers) that the resource has been permanently moved to a new location.

Practical example: Redirect root path to URL with query parameters

Suppose we need to redirect the root path of the website (e.g. https://support.example.com.br/) to a URL with specific query parameters (e.g. https://support.example.com.br/?SSO=1). This is a common requirement, perhaps for integrating single sign-on (SSO) or other specific logic.

Here is an example Nginx server block configuration that shows how to implement this redirection:

 server {
    listen 8080; # Listening port, adjust index according to actual deployment index.php index.html;
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;

    location/{
        # Redirect the root path '/' to '/?SSO=1'
        # Use the permanent flag to indicate that this is a permanent redirection rewrite ^/$ /?SSO=1 permanent;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(. \.php)(/. )$;
        fastcgi_passphp:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param SERVER_NAME $host;    
    }
    location ~ /\.ht {
        deny all;
    }
    location ~ php-errors\.log$ {
        deny all;
    }
}

Configuration details

  1. location / { ... } : This location block matches all requests and is ideal for handling root path redirects.
  2. rewrite ^/$ /?SSO=1 permanent; :
    • ^/$ : This is a regular expression that exactly matches the requested URI as the root path /.
      • ^ represents the beginning of a string.
      • $ indicates the end of the string.
      • / matches the slash character.
    • /?SSO=1 : This is the rewritten target URI. It replaces the root path with the root path with query parameter SSO=1.
    • permanent : This is the redirect flag. It tells Nginx to send an HTTP 301 (Moved Permanently) response to the client.

301 permanent redirect vs. 302 temporary redirect

The difference between permanent (301) and redirect (302) is crucial when choosing the flags for the rewrite directive:

  • HTTP 301 Moved Permanently :
    • Meaning : Tells clients and search engines that the requested resource has been permanently moved to a new URL.
    • Impact : Search engines will transfer the weight and ranking of the original URL to the new URL, helping to maintain SEO value. Browsers usually cache 301 redirects and access the new URL directly next time.
    • Applicable scenarios : permanent changes in URL structure, website migration, forced use of canonical URLs (such as HTTPS or with www).
  • HTTP 302 Found (temporary redirect) :
    • Meaning : Tells clients and search engines that the requested resource is temporarily moved to a new URL.
    • Impact : The search engine will not transfer the weight of the original URL to the new URL because it considers the change to be temporary. Browsers generally do not cache 302 redirects.
    • Applicable scenarios : A/B testing, temporary maintenance pages, jumps after users log in (you don’t want search engines to index this jump).

In the above example, if permanent is replaced with redirect, Nginx will send a 302 response. For scenarios where the root path is permanently redirected to add SSO parameters, search engines and users are usually expected to remember the new parameterized URL, so permanent is a better choice.

Things to note and best practices

  1. Test Nginx configuration : After applying any configuration changes, be sure to check that the syntax of the configuration file is correct using the sudo nginx -t command. If the test passes, use the sudo nginx -s reload or sudo systemctl reload nginx command to reload the Nginx service.
  2. Verify the redirect : Use the browser developer tools (Network tab) or the curl -I command to verify that the redirect works as expected and check the returned HTTP status code (301 or 302).
     curl -I https://support.example.com.br/

    Expected output should contain HTTP/1.1 301 Moved Permanently and Location: https://support.example.com.br/?SSO=1.

  3. Redirect loops : Configure rewrite rules carefully to avoid creating redirect loops. For example, a loop may occur if the target URL matches the same rewrite rule again.
  4. Priority of location blocks : There are priority rules for the order in which Nginx processes location blocks. Understanding these rules can help avoid unexpected redirect behavior. Generally, exact matching (=) takes precedence over prefix matching (^~), which takes precedence over regular expression matching (~ or ~*).
  5. Log analysis : Pay close attention to Nginx's access_log and error_log, which are important sources of information for debugging redirection issues.

Summarize

Through the detailed explanations and examples of this article, we have deeply explored how to use Nginx's rewrite directive to implement URL redirection, especially to redirect the root path to a URL with query parameters. Understanding the difference between the permanent and redirect flags and their impact on SEO and browser caching is key to configuring Nginx redirects that are efficient and adhere to best practices. In actual deployments, be sure to conduct adequate testing and validation to ensure that redirects behave as expected.

The above is the detailed content of NGINX URL redirection in action: detailed explanation and best practices. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement OAuth2.0 authorization code mode in PHP_PHP complete authorization process [Operation] How to implement OAuth2.0 authorization code mode in PHP_PHP complete authorization process [Operation] Apr 13, 2026 pm 11:42 PM

The authorization URL generated by PHP must contain response_type=code, client_id, redirect_uri and state; the redirect_uri must be exactly the same as the registration (including the trailing slash), and the state must be stored in $_SESSION for comparison to prevent CSRF.

Tutorial on optimizing form data interaction between jQuery AJAX and PHP Tutorial on optimizing form data interaction between jQuery AJAX and PHP Apr 09, 2026 pm 12:48 PM

For common configuration and processing issues when jQuery AJAX submits form data to a PHP page, this tutorial explains in detail the conflict between the jQuery Validation plug-in and the submit event, the correct use of contentType, and how to correctly receive data on the PHP side. At the same time, it introduces the use of FormData to achieve a more flexible and robust form submission method, and provides code examples and best practices to help developers efficiently build reliable asynchronous form submission functions.

How to get the current timestamp in PHP_How to get the current timestamp in PHP [Operation] How to get the current timestamp in PHP_How to get the current timestamp in PHP [Operation] Apr 13, 2026 pm 11:51 PM

The most direct and reliable way is to use the time() function, which returns the integer seconds since the Unix epoch, with zero parsing, zero dependencies, and no time zone impact; avoid using strtotime(‘now’) and date(‘U’), and recommend microtime(true) to obtain millisecond precision.

How to implement Eloquent Attribute Accounting in PHP_Laravel data operation audit tracking [Tutorial] How to implement Eloquent Attribute Accounting in PHP_Laravel data operation audit tracking [Tutorial] Apr 14, 2026 am 06:45 AM

Adding logs directly to Eloquent's $casts or getFooAttribute is invalid because the accessor/mutator is only triggered when the model attributes are read and written, and cannot capture batch updates, native SQL and other changes that bypass the model. The audit needs to cover all data modification scenarios.

How to safely modify table names referenced by foreign keys in Laravel migrations How to safely modify table names referenced by foreign keys in Laravel migrations Apr 17, 2026 pm 01:22 PM

This article introduces how to safely update the target table name of an existing foreign key constraint (such as changing from seller to sellers) through migration in Laravel, covering the key steps and precautions for deleting old constraints and rebuilding new constraints.

NGINX URL redirection in action: detailed explanation and best practices NGINX URL redirection in action: detailed explanation and best practices Apr 22, 2026 am 06:17 AM

This article aims to provide a professional tutorial on how to configure URL redirection using Nginx. We will focus on the use of the rewrite directive, especially how to redirect the root path to a URL with query parameters, and delve into the difference between the redirect (302 temporary redirect) and permanent (301 permanent redirect) flags and their considerations in SEO and browser caching to ensure that the Nginx configuration is both efficient and in line with best practices.

MySQL inventory entry and exit details and balance query (filtered by date and warehouse) MySQL inventory entry and exit details and balance query (filtered by date and warehouse) Apr 17, 2026 pm 01:34 PM

This article explains in detail how to use MySQL CTE and UNION ALL to build a dynamic inventory flow report, summarize the purchase (Purchase), outbound (Order) quantity and real-time balance of each commodity according to the specified date and warehouse ID, and output a structured result set that can be directly used for business dashboards.

How to implement lazy loading of images to improve long page performance How to implement lazy loading of images to improve long page performance Apr 22, 2026 am 04:26 AM

This article introduces how to use the loading="lazy" attribute of native HTML to easily load images on demand in the viewport, significantly reducing initial page resource consumption. It is especially suitable for scrolling long pages such as portfolios and galleries containing a large number of images. No JavaScript framework required and compatible with modern mainstream browsers.

Related articles