跳转至

将二级域名定向到顶级域名

本站从一开始即使用的是不加www的裸域(zimohan.com),但是由于某种要求,需要启用www二级域名与裸域同时访问。首先想到的是添加www的cname,但是zimohan.com已经添加了https支持,通过设置给www设置cname,访问的时候会报证书错误,于是改为从服务器端找突破口。

思路就是:http和https检测域名,然后跳转。

打开网站的配置文件(/etc/nginx/sites-enabled/zimohan.com.conf),我这里使用的是certbot安装的Let's Encrypt免费证书,所以在配置文件中有两个server字段,两个eerver里面都添加:

server_name zimohan.com www.zimohan.com; #添加www.zimohan.com
两个server都添加:
if ($host = www.zimohan.com) {
    return 301 https://zimohan.com$request_uri;
}
# 检测到域名为www.zimohan.com时,定向到https://zimohan.com/
完整的配置如下:
server {
    server_name zimohan.com www.zimohan.com;
    root /var/www/zimohan.com;
    index index.html index.htm index.nginx-debian.html;
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/zimohan.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/zimohan.com/privkey.pem;
    if ($host = www.zimohan.com) {
        return 301 https://zimohan.com$request_uri;
    }
}
server {
    if ($host = www.zimohan.com) {
        return 301 https://zimohan.com$request_uri;
    }
    if ($host = zimohan.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
    listen 80;
    server_name zimohan.com www.zimohan.com;
    return 404; # managed by Certbot
}