nginx 301 重定向的配置方法

无需重定向时,nginx配置两个server_namegebilao.wangwww.gebilao.wang,可以配置如下:

server {
    charset utf-8;
    listen 80;
    server_name gebilao.wang www.gebilao.wang;

    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/www/sockets/gebilao.wang.socket;
    }
}

Nginx 301 重定向 (含www的域名 重定向到 不含www的域名 ):

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

server {
    charset utf-8;
    listen 80;
    server_name gebilao.wang;

    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/www/sockets/gebilao.wang.socket;
    }
}

Nginx 301 重定向 (不含www的域名 重定向到 含www的域名 ):

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

server {
    charset utf-8;
    listen 80;
    server_name www.gebilao.wang;

    location = /favicon.ico { access_log off; log_not_found off; }

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/www/sockets/gebilao.wang.socket;
    }
}

如果你使用的是 Apache,配置方法参见: Apache 301 重定向的配置方法

更多详细内容可以参考:Efficient 301 Redirects: https://www.tinywp.in/301-redirect-wordpress/