萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

LNMP 系列教程四:Nginx 配置 301 永久重定向統一 WWW 與非 WWW 域名

為什麼需要 301 重定向?

  • SEO 權重集中,避免雙域名分散權重
  • 避免重複內容被搜尋引擎判定為作弊
  • 統一品牌入口,提升用戶信任度

WordPress 等現代 CMS 內建處理,但其他程式 (Discuz、Typecho、靜態站點) 需手動配置。

Nginx 配置範例:非 WWW 301 跳轉至 WWW

編輯 /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;
    # ... 其他配置
}

反向:WWW 301 跳轉至非 WWW (裸域)

if ($host = 'www.yourdomain.com') {
    rewrite ^/(.*)$ https://yourdomain.com/$1 permanent;
}

最佳實踐:使用 return 替代 rewrite (效能更好)

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 指向主域名。

HTTPS 環境補充

若已啟用 SSL,需在 listen 443 ssl 的 server 區塊同樣配置重定向,並確保 SSL 證書包含雙域名 (SAN) 或使用泛域名證書。

copyright © 萬盛學電腦網 all rights reserved