如何将顶级域名重定向到二级域名

2019-04-23  本文已影响0人  Hesunfly

    如果对于域名没有过多了解的人,会经常将 example.comwww.example.com 认定为相同的域名。但事实并非是如此,example.com 为顶级域名,www.example.com 为二级域名。有的人在上网时习惯性的输入 example.com 进行访问,而有的人则选择带有 www 前缀的二级域名,但是细心的人会发现,多数的知名网站都会将其重定向到带有 www 的二级域名中,这也是符合我们的使用习惯的。从开发的角度来看,这两个域名会带来跨域的问题,所以我们应该在访问 example.com 自动重定向到 www 二级域名,可以减少不必要的问题。接下来我介绍一下应该如何进行配置,我以自己的域名 hesunfly.com 为例进行介绍,使用的服务器软件为 Nginx。

登陆服务器,打开 Nginx 的域名配置文件:

# 由于使用了 https 协议,所以我们需要在此处监听80端口,将 http 重定向到https,
server {
    listen       80;
    #处理使用 http://hesunfly.com 和 http://www.hesunfly.com 域名的请求
    server_name  hesunfly.com www.hesunfly.com;
    #将请求重定向到带有 https 协议的二级域名 www.hesunfly.com  
    return 301 https://www.hesunfly.com$request_uri;
}

#处理 https 协议的 www.hesunfly.com 的请求
server {
    listen 443;
    server_name www.hesunfly.com;
    ssl on;
    ssl_certificate  根据自己情况配置;
    ssl_certificate_key 根据自己情况配置;
    ssl_session_timeout 5m;
    ssl_ciphers 根据自己情况配置;
    ssl_protocols 根据自己情况配置;
    ssl_prefer_server_ciphers on;

    root "自定义";

    charset utf-8;

    location / {
        index  index.html index.htm index.php;
        try_files $uri $uri/ /index.php?$query_string;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~* \.php$ {

    fastcgi_index index.php;

    fastcgi_pass   127.0.0.1:9000;

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    include       fastcgi_params;
    }

    location ~ /\.ht {
        deny  all;
    }
}

完成上面的配置后我们在浏览器输入 hesunfly.com 就可以看到会自动重定向到 https://www.hesunfly.com 下。可是如果用户使用 Https 输入 https://hesunfly.com 我们的重定向就不能正常使用了,所以接下来需要配置 Https 下的重定向。

#监听使用 https 协议进行访问的请求
server {
    listen  443;
    server_name hesunfly.com;
    ssl on;
    ssl_certificate  根据自己情况配置;
    ssl_certificate_key 根据自己情况配置;
    ssl_session_timeout 5m;
    ssl_ciphers 根据自己情况配置;
    ssl_protocols 根据自己情况配置;
    ssl_prefer_server_ciphers on;
   #将其重定向到 https://www.hesunfly.com 域名下
    return 301  https://www.hesunfly.com;
}

大功告成!其实也不复杂,但是自己在配置时也是踩了一些坑!

文章同步发布在我的个人博客中,传送门Hesunfly Blog

上一篇下一篇

猜你喜欢

热点阅读