Nginx (發音 "engine X") 由俄羅斯開發者 Igor Sysoev 編寫,輕量級高效能 HTTP 與反向代理伺服器,同時支援 IMAP/POP3/SMTP 代理。以事件驅動非同步架構著稱,佔用記憶體極低、並發能力極強。
location [= | ~ | ~* | ^~] /uri/ { ... }
| 修飾符 | 含義 | 優先順序 |
|---|---|---|
= | 精確匹配 | 最高 (最先檢查) |
^~ | 前綴匹配,不再檢查正則 | |
~ | 區分大小寫正則匹配 | 次之 (按配置檔順序) |
~* | 不區分大小寫正則匹配 | |
| 無修飾符 | 前綴匹配 | 最低 (若無正則匹配則用最長前綴) |
範例:
location / { } # 兜底匹配所有請求
location = / { } # 僅匹配根目錄 /
location ~* \.(gif|jpg|jpeg)$ { # 不分大小寫匹配圖片副檔名
rewrite \.(gif|jpg)$ /logo.png;
}
| 旗標 | 行為 | 對應 HTTP 狀態碼 |
|---|---|---|
last | 完成重寫,重新發起內部請求 (類 Apache [L]) | - |
break | 終止重寫,不再匹配後續規則 | - |
redirect | 臨時重導向 | 302 |
permanent | 永久重導向 | 301 |
-f / !-f # 檔案存在 / 不存在
-d / !-d # 目錄存在 / 不存在
-e / !-e # 檔案或目錄存在 / 不存在
-x / !-x # 檔案可執行 / 不可執行
$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 # 查詢字串參數
server {
listen 80;
server_name start.igrow.cn;
if ($http_host !~ "^star\.igrow\.cn$") {
rewrite ^(.*) https://star.igrow.cn$1 redirect;
}
}
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; }
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;
}
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;
}