WordPress 等現代 CMS 內建處理,但其他程式 (Discuz、Typecho、靜態站點) 需手動配置。
編輯 /usr/local/nginx/conf/vhost/yourdomain.com.conf:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# 核心重定向邏輯
if ($host != 'www.yourdomain.com') {
rewrite ^/(.*)$ https://www.yourdomain.com/$1 permanent;
}
index index.html index.htm index.php;
root /home/wwwroot/yourdomain.com;
# ... 其他配置
}
if ($host = 'www.yourdomain.com') {
rewrite ^/(.*)$ https://yourdomain.com/$1 permanent;
}
server {
listen 80;
server_name yourdomain.com;
return 301 https://www.yourdomain.com$request_uri;
}
server {
listen 80;
server_name www.yourdomain.com;
# 正常站點配置
root /home/wwwroot/yourdomain.com;
index index.php index.html;
# ...
}
/root/lnmp restart # 或 /usr/local/nginx/sbin/nginx -s reload # 驗證 curl -I https://yourdomain.com # 應返回:HTTP/1.1 301 Moved Permanently # Location: https://www.yourdomain.com/
使用站長工具「HTTP 狀態碼查詢」輸入非主域名,確認返回 301 且 Location 指向主域名。
若已啟用 SSL,需在 listen 443 ssl 的 server 區塊同樣配置重定向,並確保 SSL 證書包含雙域名 (SAN) 或使用泛域名證書。