萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Nginx 單 IP 多域名虛擬主機配置完整指南:獨立配置、合併寫法、301 跳轉與 404 定制

配置架構說明

Nginx 推薦採用 獨立配置檔 + include 機制,而非塞進單一 nginx.conf,便於版控與管理。

# 主配置 nginx.conf http 區塊
include /usr/local/nginx/conf/servers/*.conf;

場景一:單域名獨立配置檔(標準做法)

建立 /usr/local/nginx/conf/servers/www.example.com.conf:

server {
    listen 80;
    server_name www.example.com;
    index index.html index.htm index.php;
    root /home/www/example.com;
    include location.conf;  # 通用 location 規則
}

重載生效:nginx -s reload 或 systemctl reload nginx

場景二:單一檔案配置多個域名(同根目錄/同規則)

server {
    listen 80;
    server_name www.example.com;
    index index.html index.htm index.php;
    root /home/www/example.com;
    include location.conf;
}

server {
    listen 80;
    server_name api.example.com;
    index index.php;
    root /home/www/api.example.com;
    include location_api.conf;
}

建議: 不同業務域名仍拆分檔案,利用 include 共用通用規則片段。

場景三:非 www 域名 301 重導向至 www(SEO 標準化)

server {
    listen 80;
    server_name example.com;  # 無 www
    return 301 https://www.example.com$request_uri;
}
  • 使用 return 301 而非 rewrite,效能更高、語意明確
  • $request_uri 保留原始請求路徑與查詢字串
  • HTTPS 環境下記得改為 https://

場景四:自定義 404 錯誤頁面

server {
    listen 80;
    server_name www.example.com;
    root /home/www/example.com;
    index index.html;
    
    error_page 404 /404.html;
    location = /404.html {
        internal;  # 僅內部重導向可存取,防直接訪問
    }
}

確保 /home/www/example.com/404.html 存在。

進階:HTTPS + HTTP/2 + 安全標頭完整範本

server {
    listen 443 ssl http2;
    server_name www.example.com;
    
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    
    # 安全標頭
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    root /home/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    error_page 404 /404.html;
    location = /404.html { internal; }
}

常見錯誤與避坑指南

錯誤現象原因解決
新增域名不生效配置檔未放入 include 目錄、或語法錯誤nginx -t 測試、檢查 include 路徑
所有域名指向同一站點server_name 缺失或拼寫錯誤、缺少 default_server明確設定 server_name、添加 listen 80 default_server 兜底
301 跳轉循環HTTPS 站點又導向 HTTP、或雙向跳轉檢查協議一致性、使用 curl -I 追蹤
靜態檔案 404root 路徑錯誤、location 匹配順序問題絕對路徑、優先匹配精確 location

管理工具推薦

  • Nginx Proxy Manager:Web UI 管理域名、SSL、反代、重導向
  • Ansible role nginx:基礎設施即代碼批量管理
  • Certbot:自動申請/續期 Let's Encrypt 憑證

掌握 Nginx 虛擬主機配置模式,配合模組化 include 與標準化範本,即可高效管理大規模多域名站點群。

copyright © 萬盛學電腦網 all rights reserved