How to 301 Redirect Nginx to WWW Domain Using Rewrite

First, you need to define test.com and www.test.com in your domain management panel to point to your server’s IP address. You can use the nslookup command to test this:
Simply run nslookup test.com and nslookup www.test.com, and ensure both have A records pointing to the IP.

Second, we can then configure the rewrite rules in Nginx.
Open the nginx.conf file and locate your server configuration block:
 

server
{
listen 80;
server_name www.test.com test.com;
if ($host != 'www.test.com' ) {
    rewrite ^/(.*)$ http://www.test.com/$1 permanent;
}
........
 

This way, users who directly access test.com will be redirected to www.test.com.
Meaning, it redirects the non-www domain to the www domain.

Method 2: Write two server blocks in the configuration file. In the first one, only keep the non-www domain.
 

server
 {
  listen       80;
  server_name www.test.com;
 

Then add the following at the very bottom of the configuration file, and it will work.

server {
                server_name test.com;
                rewrite ^(.*) http://www.test.com/$1 permanent;
        }

If you have multiple different domains bound to the same directory and need to 301 redirect non-www to www, the method is the same as above.
Add the following at the end of the complete vhost configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server {
server_name test1.com;
rewrite ^(.*) http://www.test1.com$1 permanent;
}
 
server {
server_name test2.com;
rewrite ^(.*) http://www.test2.com$1 permanent;
}
 
server {
server_name test3.com;
rewrite ^(.*) http://www.test3.com$1 permanent;
}

A 301 permanent redirect is one of the status codes in the HTTP data stream header information returned by the server when a user or search engine requests a web page, indicating that the page has been permanently moved to another address.
A 302 temporary redirect is also a status code, meaning the page has been temporarily moved to another URL.
The main difference between the two is, in short, a 302 redirect is easily seen as spam by search engines, whereas a 301 is not.
permanent stands for 301 permanent redirect; changing it to redirect makes it a 302 temporary redirect.
Official Nginx rewrite documentation: Portal

 

This article is from Liu Rongxing's Blog. Please attribute the source and include the corresponding link when reposting.

Permanent link to this article: http://www.liurongxing.com/nginx-301-www-rewrite.html

Leave a Comment

Your email address will not be published.