最终效果是,将

http://www.xingdi.me
http://xingdi.me
www.xingdi.me
xingdi.me
https://www.xingdi.me

全部指向https://xingdi.me

只需要一个conf配置,里面配置三个server即可

第一个server监听80端口,并返回301重定向,实现前四条的重定向

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

这样以下四个url就都会跳转到https://xingdi.me对应的链接

http://www.xingdi.me
http://xingdi.me
www.xingdi.me
xingdi.me

重启nginx后可以通过curl命令测试测试

curl -I www.xingdi.me

下面添加一个server,重定向https://www.xingdi.mehttps://xingdi.me

server{
        listen 443 ssl http2;
        server_name www.xingdi.me;
        ssl_certificate /**/**/nginx/conf/ssl/xingdi.me/fullchain.cer;
        ssl_certificate_key /**/**/nginx/conf/ssl/xingdi.me/xingdi.me.key;
        return 301 https://xingdi.me$request_uri;
}

其中ssl_certificate 和 ssl_certificate_key是从最后一个server配置中拿出来的,是nginx配置https时自动生成的证书。
所以最终的配置效果如下:

server{
    listen 80;
    server_name xingdi.me www.xingdi.me;
    return 301 https://xingdi.me$request_uri;
}
server{
        listen 443 ssl http2;
        server_name www.xingdi.me;
        ssl_certificate /**/**/nginx/conf/ssl/xingdi.me/fullchain.cer;
        ssl_certificate_key /**/**/nginx/conf/ssl/xingdi.me/xingdi.me.key;
        return 301 https://xingdi.me$request_uri;
}
server{
        #默认配置
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name xingdi.me;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /**/**/**/dylan;
        ssl on;
        ssl_certificate /**/**/nginx/conf/ssl/xingdi.me/fullchain.cer;
        ssl_certificate_key /**/**/nginx/conf/ssl/xingdi.me/xingdi.me.key;
        .....
}

标签: nginx, 重定向, www, 301, https

添加新评论