????如果對于域名沒有過多了解的人乘凸,會經(jīng)常將 example.com 和 www.example.com 認(rèn)定為相同的域名模庐。但事實并非是如此唯卖,example.com 為頂級域名观谦,www.example.com 為二級域名。有的人在上網(wǎng)時習(xí)慣性的輸入 example.com 進行訪問澳窑,而有的人則選擇帶有 www 前綴的二級域名,但是細心的人會發(fā)現(xiàn),多數(shù)的知名網(wǎng)站都會將其重定向到帶有 www 的二級域名中伴鳖,這也是符合我們的使用習(xí)慣的。從開發(fā)的角度來看徙硅,這兩個域名會帶來跨域的問題榜聂,所以我們應(yīng)該在訪問 example.com 自動重定向到 www 二級域名,可以減少不必要的問題嗓蘑。接下來我介紹一下應(yīng)該如何進行配置须肆,我以自己的域名 hesunfly.com 為例進行介紹,使用的服務(wù)器軟件為 Nginx桩皿。
登陸服務(wù)器豌汇,打開 Nginx 的域名配置文件:
# 由于使用了 https 協(xié)議,所以我們需要在此處監(jiān)聽80端口泄隔,將 http 重定向到https拒贱,
server {
listen 80;
#處理使用 http://hesunfly.com 和 http://www.hesunfly.com 域名的請求
server_name hesunfly.com www.hesunfly.com;
#將請求重定向到帶有 https 協(xié)議的二級域名 www.hesunfly.com
return 301 https://www.hesunfly.com$request_uri;
}
#處理 https 協(xié)議的 www.hesunfly.com 的請求
server {
listen 443;
server_name www.hesunfly.com;
ssl on;
ssl_certificate 根據(jù)自己情況配置;
ssl_certificate_key 根據(jù)自己情況配置;
ssl_session_timeout 5m;
ssl_ciphers 根據(jù)自己情況配置;
ssl_protocols 根據(jù)自己情況配置;
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 下的重定向。
#監(jiān)聽使用 https 協(xié)議進行訪問的請求
server {
listen 443;
server_name hesunfly.com;
ssl on;
ssl_certificate 根據(jù)自己情況配置;
ssl_certificate_key 根據(jù)自己情況配置;
ssl_session_timeout 5m;
ssl_ciphers 根據(jù)自己情況配置;
ssl_protocols 根據(jù)自己情況配置;
ssl_prefer_server_ciphers on;
#將其重定向到 https://www.hesunfly.com 域名下
return 301 https://www.hesunfly.com;
}
大功告成巷燥!其實也不復(fù)雜赡盘,但是自己在配置時也是踩了一些坑!
文章同步發(fā)布在我的個人博客中缰揪,傳送門Hesunfly Blog