Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Nginx 入門教學:Location、Rewrite、Redirect、防盜鏈、快取與存取控制實戰語法

編輯:關於伺服器

Nginx 簡介

Nginx (發音 "engine X") 由俄羅斯開發者 Igor Sysoev 編寫,輕量級高效能 HTTP 與反向代理伺服器,同時支援 IMAP/POP3/SMTP 代理。以事件驅動非同步架構著稱,佔用記憶體極低、並發能力極強。

核心指令語法速查

1. Location 匹配優先順序與修飾符

location [= | ~ | ~* | ^~] /uri/ { ... }
修飾符含義優先順序
=精確匹配最高 (最先檢查)
^~前綴匹配,不再檢查正則
~區分大小寫正則匹配次之 (按配置檔順序)
~*不區分大小寫正則匹配
無修飾符前綴匹配最低 (若無正則匹配則用最長前綴)

範例:

location / { }                    # 兜底匹配所有請求
location = / { }                  # 僅匹配根目錄 /
location ~* \.(gif|jpg|jpeg)$ {   # 不分大小寫匹配圖片副檔名
    rewrite \.(gif|jpg)$ /logo.png;
}

2. Rewrite 重寫旗標

旗標行為對應 HTTP 狀態碼
last完成重寫,重新發起內部請求 (類 Apache [L])-
break終止重寫,不再匹配後續規則-
redirect臨時重導向302
permanent永久重導向301

3. 判斷條件運算子

-f / !-f   # 檔案存在 / 不存在
-d / !-d   # 目錄存在 / 不存在
-e / !-e   # 檔案或目錄存在 / 不存在
-x / !-x   # 檔案可執行 / 不可執行

4. 內建變數 (常用於條件判斷與重寫)

$host               # 請求 Host 標頭
$server_port        # 伺服器埠號
$request_uri        # 完整請求 URI (含參數)
$document_uri       # 不含參數的 URI
$document_root      # 當前請求對應 root 路徑
$request_filename   # 請求對應的完整檔案路徑
$remote_addr        # 客戶端 IP
$http_user_agent    # User-Agent
$http_referer       # Referer
$args / $query_string # 查詢字串參數

實戰配置範例

強制 HTTPS / 統一網域 (Redirect)

server {
    listen 80;
    server_name start.igrow.cn;
    if ($http_host !~ "^star\.igrow\.cn$") {
        rewrite ^(.*) https://star.igrow.cn$1 redirect;
    }
}

防盜鏈 (Referer 檢查)

location ~* \.(gif|jpg|swf)$ {
    valid_referers none blocked start.igrow.cn sta.igrow.cn;
    if ($invalid_referer) {
        rewrite ^/ https://$host/logo.png;
    }
}

靜態資源快取過期時間

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
        expires 1h;
        break;
    }
}

禁止存取特定目錄/檔案類型

# 禁止 .htaccess 等隱藏檔
location ~/\.ht { deny all; }

# 禁止多個目錄
location ~ ^/(cron|templates)/ { deny all; break; }

# 禁止 /data 開頭所有路徑 (含子目錄)
location ~ ^/data { deny all; }

# 單一目錄 (僅限該層)
location /searchword/cron/ { deny all; }

結合框架路由 (QeePHP 範例)

if (!-d $request_filename) {
    rewrite ^/([a-zA-Z]+)/([a-zA-Z]+)/?(.*)$ /index.php?namespace=user&controller=$1&action=$2&$3 last;
    rewrite ^/([a-zA-Z]+)/?$ /index.php?namespace=user&controller=$1 last;
    break;
}

子網域轉參數 (abc.domain.com/sort/2 → act=sort&cid=abc&id=2)

if ($host ~* (.*)\.domain\.com) {
    set $sub_name $1;
    rewrite ^/sort\/(\d+)\/?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
}

目錄自動補齊斜線

if (-d $request_filename) {
    rewrite ^/(.*)([^/])$ https://$host/$1$2/ permanent;
}
Copyright © Windows教程網 All Rights Reserved