案例1

http://example.com http://www.example.com https://example.com

# 重定向到

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

server {
listen 443;
server_name example.com www.example.com;
if ($host = example.com) {
return 301 https://www.example.com$request_uri;
}
}

案例2

http://example.com

# 重定向到

https://example.com
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
# 或者
return 301 https://example.com$request_uri;
}

server {
listen 443;
server_name example.com;
}

扩展

# 测试修改后的配置文件是否通过检查,是否配置错误
nginx -t

# 如果没有错误即可重载配置
nginx -s reload