Nginx下301重定向域名的方法

编辑/usr/local/nginx/conf下的nginx.conf,在server部分server_name下边添加或修改,如果是ssl,则在https部分的server的server_name下边添加或修改:

方法一:不带www跳转到带www

server {
	listen 80;
	server_name www.neirong.org neirong.org;
	return 301 http://www.neirong.org$request_uri;
}
方法二:所有域名跳转到带www
server 
	{
		listen 80;
		server_name www.neirong.org neirong.org;
		if ($host != 'www.neirong.org' ) {
			rewrite ^/(.*)$ http://www.neirong.org/$1 permanent;
		}
	}

方法三:不带www的https跳转到带www的https

在https的server部分的server_name下边添加

server
    {
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name www.neirong.org neirong.org;
		if ($host = 'neirong.org') {
		  return 301 https://www.neirong.org$request_uri;
		}
	}

方法四:http跳转到https

server 
	{
		listen 80;
		server_name www.neirong.org neirong.org;
		return 301 https://www.neirong.org$request_uri;
	}

示例(部分代码):

server {
	server_name www.neirong.org neirong.org;
	if ($host != 'www.neirong.org' ) {
		rewrite ^/(.*)$ http://www.neirong.org/$1 permanent;
	}
	...
} 
提示:如果是想让http强制跳转到https,把里面的http换成https就行。
关键词: vps linux nginx