nginx的location寫法



 

順序 no優先級:
(location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)


nginx配置location總結及rewrite規則寫法
Posted on 2015-05-17 | In Linux , Nginx | | Visitors 37242
1. location正則寫法

一個示例:

location  = / {
  # 精確匹配 / ,主機名后面不能帶任何字符串
  [ configuration A ]
}
location  / {
  # 因為所有的地址都以 / 開頭,所以這條規則將匹配到所有請求
  # 但是正則和最長字符串會優先匹配
  [ configuration B ]
}
location /documents/ {
  # 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
  # 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
  [ configuration C ]
}
location ~ /documents/Abc {
  # 匹配任何以 /documents/Abc 開頭的地址,匹配符合以后,還要繼續往下搜索
  # 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
  [ configuration CC ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 開頭的地址,匹配符合以后,停止往下搜索正則,采用這一條。
  [ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配所有以 gif,jpg或jpeg 結尾的請求
  # 然而,所有請求 /images/ 下的圖片會被 config D 處理,因為 ^~ 到達不了這一條正則
  [ configuration E ]
}
location /images/ {
  # 字符匹配到 /images/,繼續往下,會發現 ^~ 存在
  [ configuration F ]
}
location /images/abc {
  # 最長字符匹配到 /images/abc,繼續往下,會發現 ^~ 存在
  # F與G的放置順序是沒有關系的
  [ configuration G ]
}
location ~ /images/abc/ {
  # 只有去掉 config D 才有效:先最長匹配 config G 開頭的地址,繼續往下搜索,匹配到這一條正則,采用
    [ configuration H ]
}

 

繼續更好的舉例

 #指定Nginx運行的用戶和用戶組,據此可設置nginx訪問文件夾的權限,防止非法用戶訪問無權限文件夾。順便提一句,對於php工程的日志文件讀寫
#所屬用戶不是nginx,因為nginx是將php轉發給php-cgi來解析,因此用戶是php-cgi的所有者,一般是www-data
user nginx nginx;

#開啟nginx的進程數目,數目應小於等於CPU總核心數,提高程序的並發性
worker_processes 4;
 
#全局訪問和錯誤日志及其級別,[ debug | info | notice | warn | error | crit ]
access_log /var/nginx/access.log;
error_log /var/nginx/error.log warn;
#默認的日志格式設定
log_format access $remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';

#進程運行時的文件
pid /run/nginx.pid;
 
#工作模式與連接數上限
events
{
#事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
# epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;
#單個進程最大連接數(最大連接數=連接數*進程數),我的配置是768*4
worker_connections 768;
#開啟同時接受多個請求,高並發
multi_accept on; 
}
 
#設定http服務器
http
{
include mime.types; #使用MIME格式,文件擴展名與文件類型映射表
default_type application/octet-stream; #默認文件類型,文件流
#charset utf-8; #默認編碼
server_names_hash_bucket_size 128; #服務器名字的hash表大小
#設定上傳文件的大小上限為8MB
client_max_body_size 8m; 

#開啟高效文件傳輸模式,調用 sendfile 函數(zero copy 方式)來輸出文件,對於普通應用設為 on,如果用來進行下載等應用磁盤IO重負載應用,#可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載和uptime。注意:如果圖片顯示不正常把這個改成off。
sendfile on;

#設置訪問黑白名單, 文件名,大小
 white_black_list_conf conf/white.list zone=white1:4m;
 white_black_list_conf conf/black.list zone=black1:4m;
 white_list white1 on; #白名單 white1 在整個http{} 中都開啟
 black_list black1 on; #黑名單 black1 在整個http{} 中都開啟

tcp_nopush on; #防止網絡阻塞
tcp_nodelay on; #防止網絡阻塞
keepalive_timeout 65; #長連接超時時間,單位是秒
 
#開啟gzip,GNU 壓縮靜態資源,優化網站訪問速度
gzip on; #開啟gzip壓縮輸出
gzip_min_length 1k; #開啟壓縮的文件大小下限
gzip_buffers 4 16k; #設置系統獲取幾個單位的緩存用於存儲gzip的壓縮結果數據流,一次申請4*16=64k緩存
gzip_http_version 1.0;
#壓縮使用http1.0及以上的文件
gzip_comp_level 2; #壓縮等級,1-10,越大壓縮率越高
#壓縮文件類型,css,js,php,jpg,png
gzip_typestext/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png
gzip_vary on; #允許例外
gzip_disable"MISE[1-6]"#IE6及以下禁用壓縮
#limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連接數的時候需要使用
 
upstream www.xxx.com {
#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的幾率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}

#FastCGI相關參數是為了改善網站的性能:減少資源占用,提高訪問速度。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

#各服務器的配置
server
{
#默認監聽http 80端口, both ipv4 & ipv6
listen 80;
listen [::]:80 default_server ipv6only=on;
#域名可以有多個,用空格隔開
server_name www.xx.com xx.com;
index index.php;
root /data/www/xx;
#日志文件
 access_log  /usr/share/nginx/logs/pc_access.log;
 error_log  /usr/share/nginx/logs/pc_error.log;

#手機端導向另一個頁面
 location / {
#判斷訪問終端類型
        if ($http_user_agent ~* '(Android|iPhone|iPad|webOS|iPod|BlackBerry)') {
                rewrite ^.+ http://m.xx.com;
        }
            root   /usr/share/nginx/html;
            index  index.php index.html index.htm;
        }
#靜態文件直接訪問 
#圖片緩存時間設置, 類似於html頁面meta標簽,可設置expire or max-age
location ~ \.(html|htm|gif|jpg|jpeg|png|bmp|swf)$ {
expires 10d;
                root /usr/share/nginx/html;
       }
#php導向9000 端口
location ~ \.php$ {
                root           /usr/share/nginx/html;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini


                # With php5-cgi alone:
                fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                #fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include fastcgi_params;
        }


#JS和CSS緩存時間設置
location ~ .*.(js|css)?$
{
expires 1h;
}
#錯誤頁面
 error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/html;
        }
#對 "/" 啟用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;
client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
client_body_buffer_size 128k; #緩沖區代理緩沖用戶端請求的最大字節數,
proxy_connect_timeout 90; #nginx跟后端服務器連接超時時間(代理連接超時)
proxy_send_timeout 90; #后端服務器數據回傳時間(代理發送超時)
proxy_read_timeout 90; #連接成功后,后端服務器響應時間(代理接收超時)
proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
proxy_buffers 4 32k; #proxy_buffers緩沖區,網頁平均在32k以下的設置
proxy_busy_buffers_size 64k; #高負荷下緩沖大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;
#設定緩存文件夾大小,大於這個值,將從upstream服務器傳
}

#設定查看Nginx狀態的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file confpasswd;
#htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
}
 
#如果使用j2ee, 可將頁面導向8080端口,所有jsp的頁面均交由tomcat或resin處理
location ~  \.(jsp|jspx|do|action)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
}

#再設置一個移動端訪問的server, 接過手機端訪問主站導來的請求
 server {
        listen       80;
        server_name m.xx.com www.m.xx.com;

        access_log  /usr/share/nginx/logs/mobile_access.log;
        error_log  /usr/share/nginx/logs/mobile_error.log;

        location / {
            root  /usr/share/nginx/html/mobile;
            index  index.html index.htm;
        }
        location ~ \.(html|htm|gif|jpg|png)$ {
                root /usr/share/nginx/html/mobile;
        }

        location ~ \.php$ {
                root  /usr/share/nginx/html/mobile;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                # With php5-cgi alone:
                fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                #fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}

 

https://www.cnblogs.com/swing07/p/5381772.html

 


location ~* /js/.*/\.js

    已=開頭表示精確匹配
    如 A 中只匹配根目錄結尾的請求,后面不能帶任何字符串。
    ^~ 開頭表示uri以某個常規字符串開頭,不是正則匹配
    ~ 開頭表示區分大小寫的正則匹配;
    ~* 開頭表示不區分大小寫的正則匹配
    / 通用匹配, 如果沒有其它匹配,任何請求都會匹配到

順序 no優先級:
(location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)

上面的匹配結果
按照上面的location寫法,以下的匹配示例成立:

    / -> config A
    精確完全匹配,即使/index.html也匹配不了
    /downloads/download.html -> config B
    匹配B以后,往下沒有任何匹配,采用B
    /images/1.gif -> configuration D
    匹配到F,往下匹配到D,停止往下
    /images/abc/def -> config D
    最長匹配到G,往下匹配D,停止往下
    你可以看到 任何以/images/開頭的都會匹配到D並停止,FG寫在這里是沒有任何意義的,H是永遠輪不到的,這里只是為了說明匹配順序
    /documents/document.html -> config C
    匹配到C,往下沒有任何匹配,采用C
    /documents/1.jpg -> configuration E
    匹配到C,往下正則匹配到E
    /documents/Abc.jpg -> config CC
    最長匹配到C,往下正則順序匹配到CC,不會往下到E

實際使用建議

所以實際使用中,個人覺得至少有三個匹配規則定義,如下:
#直接匹配網站根,通過域名訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。
#這里是直接轉發給后端應用服務器了,也可以是一個靜態首頁
# 第一個必選規則
location = / {
    proxy_pass http://tomcat:8080/index
}
# 第二個必選規則是處理靜態文件請求,這是nginx作為http服務器的強項
# 有兩種配置模式,目錄匹配或后綴匹配,任選其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三個規則就是通用規則,用來轉發動態請求到后端應用服務器
#非靜態文件請求就默認是動態請求,自己根據實際把握
#畢竟目前的一些框架的流行,帶.php,.jsp后綴的情況很少了
location / {
    proxy_pass http://tomcat:8080/
}

http://tengine.taobao.org/book/chapter_02.html
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
2. Rewrite規則

rewrite功能就是,使用nginx提供的全局變量或自己設置的變量,結合正則表達式和標志位實現url重寫以及重定向。rewrite只能放在server{},location{},if{}中,並且只能對域名后邊的除去傳遞的參數外的字符串起作用,例如 http://seanlook.com/a/we/index.php?id=1&u=str 只對/a/we/index.php重寫。語法rewrite regex replacement [flag];

如果相對域名或參數字符串起作用,可以使用全局變量匹配,也可以使用proxy_pass反向代理。

表明看rewrite和location功能有點像,都能實現跳轉,主要區別在於rewrite是在同一域名內更改獲取資源的路徑,而location是對一類路徑做控制訪問或反向代理,可以proxy_pass到其他機器。很多情況下rewrite也會寫在location里,它們的執行順序是:

    執行server塊的rewrite指令
    執行location匹配
    執行選定的location中的rewrite指令

如果其中某步URI被重寫,則重新循環執行1-3,直到找到真實存在的文件;循環超過10次,則返回500 Internal Server Error錯誤。
2.1 flag標志位

    last : 相當於Apache的[L]標記,表示完成rewrite
    break : 停止執行當前虛擬主機的后續rewrite指令集
    redirect : 返回302臨時重定向,地址欄會顯示跳轉后的地址
    permanent : 返回301永久重定向,地址欄會顯示跳轉后的地址

因為301和302不能簡單的只返回狀態碼,還必須有重定向的URL,這就是return指令無法返回301,302的原因了。這里 last 和 break 區別有點難以理解:

    last一般寫在server和if中,而break一般使用在location中
    last不終止重寫后的url匹配,即新的url會再從server走一遍匹配流程,而break終止重寫后的匹配
    break和last都能組織繼續執行后面的rewrite指令

2.2 if指令與全局變量

if判斷指令
語法為if(condition){...},對給定的條件condition進行判斷。如果為真,大括號內的rewrite指令將被執行,if條件(conditon)可以是如下任何內容:

    當表達式只是一個變量時,如果值為空或任何以0開頭的字符串都會當做false
    直接比較變量和內容時,使用=或!=
    ~正則表達式匹配,~*不區分大小寫的匹配,!~區分大小寫的不匹配

-f和!-f用來判斷是否存在文件
-d和!-d用來判斷是否存在目錄
-e和!-e用來判斷是否存在文件或目錄
-x和!-x用來判斷文件是否可執行

例如:

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
} //如果UA包含"MSIE",rewrite請求到/msid/目錄下
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
 } //如果cookie匹配正則,設置變量$id等於正則引用部分
if ($request_method = POST) {
    return 405;
} //如果提交方法為POST,則返回狀態405(Method not allowed)。return不能返回301,302
if ($slow) {
    limit_rate 10k;
} //限速,$slow可以通過 set 指令設置
if (!-f $request_filename){
    break;
    proxy_pass  http://127.0.0.1;
} //如果請求的文件名不存在,則反向代理到localhost 。這里的break也是停止rewrite檢查
if ($args ~ post=140){
    rewrite ^ http://example.com/ permanent;
} //如果query string中包含"post=140",永久重定向到example.com
location ~* \.(gif|jpg|png|swf|flv)$ {
    valid_referers none blocked www.jefflei.com www.leizhenfang.com;
    if ($invalid_referer) {
        return 404;
    } //防盜鏈
}

全局變量
下面是可以用作if判斷的全局變量

    $args : #這個變量等於請求行中的參數,同$query_string
    $content_length : 請求頭中的Content-length字段。
    $content_type : 請求頭中的Content-Type字段。
    $document_root : 當前請求在root指令中指定的值。
    $host : 請求主機頭字段,否則為服務器名稱。
    $http_user_agent : 客戶端agent信息
    $http_cookie : 客戶端cookie信息
    $limit_rate : 這個變量可以限制連接速率。
    $request_method : 客戶端請求的動作,通常為GET或POST。
    $remote_addr : 客戶端的IP地址。
    $remote_port : 客戶端的端口。
    $remote_user : 已經經過Auth Basic Module驗證的用戶名。
    $request_filename : 當前請求的文件路徑,由root或alias指令與URI請求生成。
    $scheme : HTTP方法(如http,https)。
    $server_protocol : 請求使用的協議,通常是HTTP/1.0或HTTP/1.1。
    $server_addr : 服務器地址,在完成一次系統調用后可以確定這個值。
    $server_name : 服務器名稱。
    $server_port : 請求到達服務器的端口號。
    $request_uri : 包含請求參數的原始URI,不包含主機名,如:”/foo/bar.php?arg=baz”。
    $uri : 不帶請求參數的當前URI,$uri不包含主機名,如”/foo/bar.html”。
    $document_uri : 與$uri相同。

例:http://localhost:88/test1/test2/test.php
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php
2.3 常用正則

    . : 匹配除換行符以外的任意字符
    ? : 重復0次或1次
    + : 重復1次或更多次
    * : 重復0次或更多次
    \d :匹配數字
    ^ : 匹配字符串的開始
    $ : 匹配字符串的介紹
    {n} : 重復n次
    {n,} : 重復n次或更多次
    [c] : 匹配單個字符c
    [a-z] : 匹配a-z小寫字母的任意一個

小括號()之間匹配的內容,可以在后面通過$1來引用,$2表示的是前面第二個()里的內容。正則里面容易讓人困惑的是\轉義特殊字符。
2.4 rewrite實例

例1:

http {
    # 定義image日志格式
    log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
    # 開啟重寫日志
    rewrite_log on;
    server {
        root /home/www;
        location / {
                # 重寫規則信息
                error_log logs/rewrite.log notice;
                # 注意這里要用‘’單引號引起來,避免{}
                rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;
                # 注意不能在上面這條規則后面加上“last”參數,否則下面的set指令不會執行
                set $image_file $3;
                set $image_type $4;
        }
        location /data {
                # 指定針對圖片的日志格式,來分析圖片類型和大小
                access_log logs/images.log mian;
                root /data/images;
                # 應用前面定義的變量。判斷首先文件在不在,不在再判斷目錄在不在,如果還不在就跳轉到最后一個url里
                try_files /$arg_file /image404.html;
        }
        location = /image404.html {
                # 圖片不存在返回特定的信息
                return 404 "image not found\n";
        }
}

對形如/images/ef/uh7b3/test.png的請求,重寫到/data?file=test.png,於是匹配到location /data,先看/data/images/test.png文件存不存在,如果存在則正常響應,如果不存在則重寫tryfiles到新的image404 location,直接返回404狀態碼。

例2:

rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;

對形如/images/bla_500x400.jpg的文件請求,重寫到/resizer/bla.jpg?width=500&height=400地址,並會繼續嘗試匹配location。


原文鏈接地址:http://seanlook.com/2015/05/17/nginx-location-rewrite/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM