nginx 反向代理和負載均衡策略配置實戰(zhàn)案例,Nginx配置SSL訪問,nginx匹配規(guī)則說明以及匹配的優(yōu)先級

本文主要包含

1.Nginx配置文件詳解

2.Nginx實現(xiàn)負載均衡

3.Nginx前端項目部署

4.Nginx配置SSL訪問

5.nginx匹配規(guī)則說明以及匹配的優(yōu)先級

首先Nginx能做反向代理【關(guān)于反向代理和正向代理此處不做說明了,感興趣的小伙伴自行谷歌】;比方說,我想在本地使用 www.google.com 的域名去訪問www.taobao.com。那么這個時候我們就可以通過nginx去實現(xiàn)
再者Nginx能實現(xiàn)負載均衡,就是說應(yīng)用部署在不同的服務(wù)器上,但是通過統(tǒng)一的域名進入,nginx則對請求進行分發(fā),將請求分發(fā)到不同的服務(wù)器上去處理,這樣就可以有效的減輕了單臺服務(wù)器的壓力,解決單點故障,在上面這兩種情況下,nginx服務(wù)器的作用都只是作為分發(fā)服務(wù)器,真正的內(nèi)容,我們可以放在其他的服務(wù)器上,這樣來,還能起到一層安全隔壁的作用,nginx可以作為隔離層

解決跨域問題

同源:URL由協(xié)議、域名、端口和路徑組成,如果兩個URL的協(xié)議、域名和端口相同,則表示他們同源
瀏覽器的同源策略:瀏覽器的同源策略,限制了來自不同源的"document"或腳本,對當前"document"讀取或設(shè)置某些屬性。
從一個域上加載的腳本不允許訪問另外一個域的文檔屬性(同源表示:協(xié)議、域名和端口相同)
例如:因為nginx和tomcat不能共用同一端口,url一樣,端口不同,這樣就會有跨域問題

Nginx配置文件

配置文件主要由四部分組成:
main(全區(qū)設(shè)置)
server(主機配置)
http(控制著nginx http處理的所有核心特性)
location(URL匹配特定位置設(shè)置)。

upstream(負載均衡服務(wù)器設(shè)置)
#Nginx的worker進程運行用戶以及用戶組
#user  nobody;

#Nginx開啟的進程數(shù)
worker_processes  1;

#定義全局錯誤日志定義類型,[debug|info|notice|warn|crit]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#指定進程ID存儲文件位置
#pid        logs/nginx.pid;

#事件配置
events {
    #use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
    #epoll模型是Linux內(nèi)核中的高性能網(wǎng)絡(luò)I/O模型,如果在mac上面,就用kqueue模型。
    use kqueue;

    #每個進程可以處理的最大連接數(shù),理論上每臺nginx服務(wù)器的最大連接數(shù)為worker_processes*worker_connections。理論值:worker_rlimit_nofile/worker_processes
    worker_connections  1024;
}

#http參數(shù)
http {
    #文件擴展名與文件類型映射表
    include       mime.types;
    #默認文件類型
    default_type  application/octet-stream;

    #日志相關(guān)定義
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #連接日志的路徑,指定的日志格式放在最后。
    #access_log  logs/access.log  main;

    #開啟高效傳輸模式
    sendfile        on;

    #防止網(wǎng)絡(luò)阻塞
    #tcp_nopush     on;

    #客戶端連接超時時間,單位是秒
    #keepalive_timeout  0;
    keepalive_timeout  65;

    #開啟gzip壓縮輸出
    #gzip  on;

    #虛擬主機基本設(shè)置
    server {
        #監(jiān)聽的端口號
        listen       80;
        #訪問域名
        server_name  localhost;

        #編碼格式,如果網(wǎng)頁格式與當前配置的不同的話將會被自動轉(zhuǎn)碼
        #charset koi8-r;

        #虛擬主機訪問日志定義
        #access_log  logs/host.access.log  main;

        #對URL進行匹配
        location / {
            #訪問路徑,可相對也可絕對路徑
            root   html;
            #首頁文件,匹配順序按照配置順序匹配
            index  index.html index.htm;
        }

        #錯誤信息返回頁面
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        #訪問URL以.php結(jié)尾則自動轉(zhuǎn)交給127.0.0.1
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        # location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        # }

        # php腳本請求全部轉(zhuǎn)發(fā)給FastCGI處理
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # 禁止訪問.ht頁面
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    #第二個虛擬主機配置
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    #HTTPS虛擬主機定義
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include servers/*;
}

反向代理實例---》假設(shè)現(xiàn)在代理 www.baidu.com

server {
    # 監(jiān)聽80端口
    listen 80;
    server_name localhost;
     # individual nginx logs for this web vhost
    access_log /tmp/access.log;
    error_log  /tmp/error.log ;
 
    # 配置代理
    location / {
        proxy_pass http://www.baidu.com;
    }

負載均衡實例 (下面主要驗證最常用的三種負載策略。虛擬主機配置)

server {
    #監(jiān)聽80端口
    listen 80;
    server_name localhost;

    # individual nginx logs for this web vhost
    access_log /tmp/access.log;
    error_log  /tmp/error.log ;

    location / {
        # 負載均衡策略
        # 輪詢 
        # proxy_pass http://polling_strategy;

        # weight權(quán)重
        # proxy_pass http://weight_strategy;

        # ip_hash
        # proxy_pass http://ip_hash_strategy;

        # fair
        # proxy_pass http://fair_strategy;

        # url_hash
        # proxy_pass http://url_hash_strategy;
        # 重定向
        # rewrite ^ http://localhost:8080;
    }

輪詢策略

# 1、輪詢(默認)
# 每個請求按時間順序逐一分配到不同的后端服務(wù)器,如果后端服務(wù)器down掉,能自動剔除。 
upstream polling_strategy { 
    server www.net:8080; # 應(yīng)用服務(wù)器1
    server www.net:8081; # 應(yīng)用服務(wù)器2
} 

測試結(jié)果(通過端口號來區(qū)分當前訪問):
8081:hello
8080:hello
8081:hello
8080:hello

權(quán)重策略

#2、指定權(quán)重
# 指定輪詢幾率,weight和訪問比率成正比,用于后端服務(wù)器性能不均的情況。 
upstream  weight_strategy { 
    server glmapper.net:8080 weight=1; # 應(yīng)用服務(wù)器1
    server glmapper.net:8081 weight=9; # 應(yīng)用服務(wù)器2
}
測試結(jié)果:總訪問次數(shù)15次,根據(jù)上面的權(quán)重配置,兩臺機器的訪問比重:2:13

ip hash策略

iphash 算法: ip是基本的點分十進制,將ip的前三個端作為參數(shù)加入hash函數(shù)。這樣做的目的是保證ip地址前三位相同的用戶經(jīng)過hash計算將分配到相同的后端server。作者的這個考慮是極為可取的,因此ip地址前三位相同通常意味著來著同一個局域網(wǎng)或者相鄰區(qū)域,使用相同的后端服務(wù)讓nginx在一定程度上更具有一致性
假設(shè)5臺機器均在同一個局域網(wǎng)內(nèi)【192.168.0.X】測試時發(fā)現(xiàn)5臺機器每次都路由到了同一個服務(wù)器上,一開始以為是配置問題,但是排查之后也排除了這個可能性。最后考慮到可能是對于同網(wǎng)段的ip做了特殊處理,驗證之后確認了猜測

#3、IP綁定 ip_hash
#每個請求按訪問ip的hash結(jié)果分配,這樣每個訪客固定訪問一個后端服務(wù)器,
#可以解決session的問題;在不考慮引入分布式session的情況下,
#原生HttpSession只對當前servlet容器的上下文環(huán)境有效
upstream ip_hash_strategy { 
    ip_hash; 
    server glmapper.net:8080; # 應(yīng)用服務(wù)器1
    server glmapper.net:8081; # 應(yīng)用服務(wù)器2
} 

其他負載均衡策略

#4、fair(第三方)
#按后端服務(wù)器的響應(yīng)時間來分配請求,響應(yīng)時間短的優(yōu)先分配。 
upstream fair_strategy { 
    server glmapper.net:8080; # 應(yīng)用服務(wù)器1
    server glmapper.net:8081; # 應(yīng)用服務(wù)器2
    fair; 
} 
#5、url_hash(第三方)
#按訪問url的hash結(jié)果來分配請求,使每個url定向到同一個后端服務(wù)器,
#后端服務(wù)器為緩存時比較有效。 
upstream url_hash_strategy { 
    server glmapper.net:8080; # 應(yīng)用服務(wù)器1
    server glmapper.net:8081; # 應(yīng)用服務(wù)器2 
    hash $request_uri; 
    hash_method crc32; 
} 

重定向rewrite

驗證思路:本地使用localhost:80端口進行訪問,根據(jù)nginx的配置,如果重定向沒有生效,則最后會停留在當前l(fā)ocalhost:80這個路徑,瀏覽器中的地址欄地址不會發(fā)生改變;如果生效了則地址欄地址變?yōu)閘ocalhost:8080;

通過驗證,滿足預期!

location / {
    #重定向
    #rewrite ^ http://localhost:8080;
}

nginx配置Vue前端發(fā)布history模式訪問

# nginx配置history模式訪問:
server {    
    listen       900;    
    server_name  localhost;      
    error_page   500 502 503 504  /50x.html;     
    location  / {         
    root   C:/Users/lenovo/Desktop/前端代碼/dist;  
    index /index.html;   try_files $uri $uri/ /index.html; 
    }
 }

nginx配置靜態(tài)資源文件映射

##靜態(tài)資源文件:
server{    
  listen 9998;   
 server_name localhost;       
 location /file {         
         add_header 'Access-Control-Allow-Origin' '*';         
         add_header 'Access-Control-Allow-Credentials' 'true';         
         add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';         
         add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';       

         # 文件夾路徑
         alias  C:/Users/lenovo/Desktop/TestRes/;      
         autoindex on;         
         autoindex_exact_size on;        
         autoindex_localtime on;    
     } 
}

實際線上Nginx配置文件參考


user root;
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    client_max_body_size 4096m;

    server {
        listen       1000;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # 配置前端Vue的dist包發(fā)布 
        location / {
            root   /usr/local/vue/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        # 轉(zhuǎn)發(fā)后端Nginx請求 
        location /service/ {
            proxy_pass http://localhost:3389/;
        }

        # 配置文件路徑映射      
        location /files {
           alias /usr/local/resource/;
           autoindex on;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


   #以下屬性中,以ssl開頭的屬性表示與證書配置有關(guān)。
   server {
        listen 6666 ssl;
        # listen 443 ssl;
        
        #配置HTTPS的默認訪問端口為443。
        #如果未在此處配置HTTPS的默認訪問端口,可能會造成Nginx無法啟動。
        #如果您使用Nginx 1.15.0及以上版本,請使用listen 443 ssl代替listen 443和ssl on
        
        server_name www.test.cn; #需要將www.test.cn替換成證書綁定的域名。
        root html;
        index index.html index.htm;

        # cert為當前路徑的文件夾
        ssl_certificate cert/www.test.cn.pem;  #需要將www.test.cn.pem替換成已上傳的證書文件的名稱。
        ssl_certificate_key cert/www.test.cn.key; #需要將www.test.cn.key替換成已上傳的證書私鑰文件的名稱。
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
     
        #表示使用的加密套件的類型。
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #表示使用的TLS協(xié)議的類型。
        ssl_prefer_server_ciphers on;
    
        location /base {
              root html;  #站點目錄。
              index index.html index.htm;
           }

        location / {
            root   /usr/local/vue/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

       location /service/ {
            proxy_pass http://localhost:3389/;
       }

       location /files {
           alias /usr/local/static/;
           autoindex on;
       } 
  }

 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}



    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


}

后臺服務(wù)訪問代理配置


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8988;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
                        
                        client_max_body_size 100m;
                        proxy_pass http://127.0.0.1/mobile/;
                        proxy_redirect    off;
                        proxy_read_timeout 3600;
                        proxy_send_timeout 3600;
                        proxy_buffer_size  128k;
                        proxy_buffers   32 32k;
                        proxy_busy_buffers_size 128k;
                        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
                        proxy_set_header  X-Real-IP  $remote_addr;
                        proxy_set_header  Host $host:$server_port;
        }

        location /etc    {
                        client_max_body_size 100m;
                        proxy_pass http://127.0.0.1/api/notice;
                        proxy_redirect    off;
                        proxy_read_timeout 3600;
                        proxy_send_timeout 3600;
                        proxy_buffer_size  128k;
                        proxy_buffers   32 32k;
                        proxy_busy_buffers_size 128k;
                        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
                        proxy_set_header  X-Real-IP  $remote_addr;
                        proxy_set_header  Host $host:$server_port;
        }
        
location /fileResult {         
         add_header 'Access-Control-Allow-Origin' '*';         
         add_header 'Access-Control-Allow-Credentials' 'true';         
         add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';         
         add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';       

        alias  /root/fileResult ;      
         autoindex on;         
         autoindex_exact_size on;        
         autoindex_localtime on;    
        } 
        
    location /fileLocal {         
         add_header 'Access-Control-Allow-Origin' '*';         
         add_header 'Access-Control-Allow-Credentials' 'true';         
         add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';         
         add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';       

         # 文件路徑
         alias  /root/local;      
         autoindex on;         
         autoindex_exact_size on;        
         autoindex_localtime on;    
        } 
        
        
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

Nginx調(diào)優(yōu)

增加工作線程數(shù)和并發(fā)連接數(shù)
[root@localhost /]# vi /etc/nginx/nginx.conf
worker_processes  4; # 一般CPU 是幾核就設(shè)置為幾 也可以設(shè)置成auto
events {
    worker_connections  10240; # 每個進程打開的最大連接數(shù),包含了 Nginx 與客戶端和 Nginx 與 upstream 之間的連接
    multi_accept on; # 可以一次建立多個連接
    use epoll;   #epoll這種網(wǎng)絡(luò)模型
}
查看nginx 語法是否正確
[root@localhost /]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
啟用長連接
[root@localhost /]# vi /etc/nginx/nginx.conf
配置反向代理
upstream server_pool{
    server localhost:8080 weight=1 max_fails=2 fail_timeout=30s;
    server localhost:8081 weight=1 max_fails=2 fail_timeout=30s;
    keepalive 300; # 300個長連接 提高效率
}
配置反向代理服務(wù)
location / {
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_pass http://server_pool;  #所有請求都代理給server_pool
}
配置壓縮
gzip on;
gzip_http_version 1.1;
gzip_disable "MSIE [1-6].(?!.*SV1)";
gzip_proxied any;
gzip_types text/plain text/css application/javascript application/x-javascript application/json application/xml application/vnd.ms-fontobject application/x-font-ttf application/svg+xml application/x-icon;
gzip_vary on;
gzip_static on;
操作系統(tǒng)優(yōu)化
 配置文件/etc/sysctl.conf
sysctl -w net.ipv4.tcp_syncookies=1 # 防止一個套接字在有過多試圖連接到時引起過載
sysctl -w net.core.somaxconn=1024 # 默認128,操作系統(tǒng)連接隊列
sysctl -w net.ipv4.tcp_fin_timeout=10 # timewait 的超時時間
sysctl -w net.ipv4.tcp_tw_reuse=1 # os 直接使用 timewait的連接
sysctl -w net.ipv4.tcp_tw_recycle=0 # 回收禁用
 /etc/security/limits.conf
           hard    nofile            204800
            soft    nofile             204800
            soft    core             unlimited
             soft    stack             204800
其它優(yōu)化
sendfile    on; # 減少文件在應(yīng)用和內(nèi)核之間拷貝
tcp_nopush  on; # 當數(shù)據(jù)包達到一定大小再發(fā)送
tcp_nodelay off; # 有數(shù)據(jù)隨時發(fā)送

Nginx匹配規(guī)則說明以及匹配的優(yōu)先級

location 匹配規(guī)則
語法規(guī)則

    location [=|~|~*|^~] /uri/ { … }

模式    含義
location = /uri    = 表示精確匹配,只有完全匹配上才能生效
location ^~ /uri    ^~ 開頭對URL路徑進行前綴匹配,并且在正則之前。
location ~ pattern    開頭表示區(qū)分大小寫的正則匹配
location ~* pattern    開頭表示不區(qū)分大小寫的正則匹配
location /uri    不帶任何修飾符,也表示前綴匹配,但是在正則匹配之后
location /    通用匹配,任何未匹配到其它location的請求都會匹配到,相當于switch中的default

前綴匹配時,Nginx 不對 url 做編碼,因此請求為 /static/20%/aa,
可以被規(guī)則 ^~ /static/ /aa 匹配到(注意是空格)

多個 location 配置的情況下匹配順序為(參考資料而來):

    首先精確匹配 =
    其次前綴匹配 ^~
    其次是按文件中順序的正則匹配
    然后匹配不帶任何修飾的前綴匹配。
    最后是交給 / 通用匹配
    當有匹配成功時候,停止匹配,按當前匹配規(guī)則處理請求

注意:前綴匹配,如果有包含關(guān)系時,按最大匹配原則進行匹配。
比如在前綴匹配:location /dir01 與location /dir01/dir02,
如有請求 http://localhost/dir01/dir02/file 將最終匹配到 location /dir01/dir02

例子,有如下匹配規(guī)則:

location = / {
   echo "規(guī)則A";
}
location = /login {
   echo "規(guī)則B";
}
location ^~ /static/ {
   echo "規(guī)則C";
}
location ^~ /static/files {
    echo "規(guī)則X";
}
location ~ .(gif|jpg|png|js|css)$ {
   echo "規(guī)則D";
}
location ~* .png$ {
   echo "規(guī)則E";
}
location /img {
    echo "規(guī)則Y";
}
location / {
   echo "規(guī)則F";
}

那么產(chǎn)生的效果如下:

訪問根目錄 /,比如 http://localhost/ 將匹配 規(guī)則A
訪問 http://localhost/login 將匹配 規(guī)則B
訪問 http://localhost/register 則匹配 規(guī)則F
訪問 http://localhost/static/a.html 將匹配 規(guī)則C
訪問 http://localhost/static/files/a.exe 將匹配 規(guī)則X,雖然 規(guī)則C 也能匹配到,
但因為最大匹配原則,最終選中了 規(guī)則X。你可以測試下,去掉規(guī)則 X ,則當前 URL 會匹配上 規(guī)則C。

訪問 http://localhost/a.gif, http://localhost/b.jpg 將匹配 規(guī)則D 和 規(guī)則 E ,
但是 規(guī)則 D 順序優(yōu)先,規(guī)則 E 不起作用,而 http://localhost/static/c.png 則優(yōu)先匹配到 規(guī)則 C

訪問 http://localhost/a.PNG 則匹配 規(guī)則 E ,而不會匹配 規(guī)則 D ,因為 規(guī)則 E 不區(qū)分大小寫。

訪問 http://localhost/img/a.gif 會匹配上 規(guī)則D,雖然 規(guī)則Y 也可以匹配上,
但是因為正則匹配優(yōu)先,而忽略了 規(guī)則Y。

訪問 http://localhost/img/a.tiff 會匹配上 規(guī)則Y。

訪問 http://localhost/category/id/1111 則最終匹配到規(guī)則 F ,因為以上規(guī)則都不匹配,
這個時候應(yīng)該是 Nginx 轉(zhuǎn)發(fā)請求給后端應(yīng)用服務(wù)器,
比如 FastCGI(php),tomcat(jsp),Nginx 作為反向代理服務(wù)器存在。

所以實際使用中,筆者覺得至少有三個匹配規(guī)則定義,如下:

# 直接匹配網(wǎng)站根,通過域名訪問網(wǎng)站首頁比較頻繁,使用這個會加速處理,官網(wǎng)如是說。
# 這里是直接轉(zhuǎn)發(fā)給后端應(yīng)用服務(wù)器了,也可以是一個靜態(tài)首頁
# 第一個必選規(guī)則
location = / {
    proxy_pass http://tomcat:8080/index
}

# 第二個必選規(guī)則是處理靜態(tài)文件請求,這是 nginx 作為 http 服務(wù)器的強項
# 有兩種配置模式,目錄匹配或后綴匹配,任選其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* .(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}

# 第三個規(guī)則就是通用規(guī)則,用來轉(zhuǎn)發(fā)動態(tài)請求到后端應(yīng)用服務(wù)器
# 非靜態(tài)文件請求就默認是動態(tài)請求,自己根據(jù)實際把握
# 畢竟目前的一些框架的流行,帶.php、.jsp后綴的情況很少了
location / {
    proxy_pass http://tomcat:8080/
}

rewrite 語法

    last – 基本上都用這個 Flag
    break – 中止 Rewirte,不再繼續(xù)匹配
    redirect – 返回臨時重定向的 HTTP 狀態(tài) 302
    permanent – 返回永久重定向的 HTTP 狀態(tài) 301

1、下面是可以用來判斷的表達式:

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

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

    例:http://localhost:88/test1/test2/test.php?k=v
    $host:localhost
    $server_port:88
    $request_uri:/test1/test2/test.php?k=v
    $document_uri:/test1/test2/test.php
    $document_root:D: ginx/html
    $request_filename:D: ginx/html/test1/test2/test.php

redirect 語法

server {
    listen 80;
    server_name start.igrow.cn;
    index index.html index.php;
    root html;
    if ($http_host !~ "^star.igrow.cn$") {
        rewrite ^(.*) http://star.igrow.cn$1 redirect;
    }
}

防盜鏈

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

根據(jù)文件類型設(shè)置過期時間

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

禁止訪問某個目錄

location ~* .(txt|doc)${
    root /data/www/wwwroot/linuxtone/test;
    deny all;
}
---------------------
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容