Nginx: 301 Redirect To A Domain Name

Nginx: 301 Redirect To A Domain Name

To perform a 301 redirect to a domain name with Nginx, you can use the return directive in the server block configuration file for the domain you want to redirect from. For example, if you want to redirect from olddomain.com to newdomain.com, you would add the following code to the server block configuration file for olddomain.com:

server {
    ...

    return 301 $scheme://newdomain.com$request_uri;
}
Source:‮‬www.lautturi.com

This code redirects all traffic from olddomain.com to newdomain.com using a 301 permanent redirect. The $scheme variable represents the protocol (e.g. http or https), and the $request_uri variable represents the rest of the URL, including the path and query string.

Once you have added this code to the server block configuration file, you need to restart Nginx for the changes to take effect. You can do this by running the following command:

sudo service nginx restart

You can also use the rewrite directive instead of the return directive to perform the redirect. For example:

server {
    ...

    rewrite ^ $scheme://newdomain.com$request_uri permanent;
}

This code uses a regular expression to match all requests and redirect them to newdomain.com. The permanent flag specifies that the redirect is permanent.

For more information on configuring redirects with Nginx, see the Nginx documentation.

Created Time:2017-10-18 14:57:43  Author:lautturi