Nginx高階用法(二)

關於favicon.ico

favicon.ico 文件是瀏覽器收藏網址時顯示的圖標,當客戶端使用瀏覽器問頁面時,瀏覽器會本身主動發起請求獲取頁面的favicon.ico文件,可是當瀏覽器請求的favicon.ico文件不存在時,服務器會記錄404日誌,並且瀏覽器也會顯示404報錯。html

具體配置

# 一:服務器不記錄訪問日誌:
        # location = /favicon.ico {
        #   log_not_found off;
        #   access_log off;
        # }
# 二:將圖標保存到指定目錄訪問:
        # location ~ ^/favicon\.ico$ {
        location = /favicon.ico {
          root /data/nginx/images123;
        }

顯示效果

Nginx高階用法(二)

修改Nginx Server版本信息

# 修改Nginx源碼文件,此配置文件須要在nginx.conf的http中添加server_tokens  off;開啓nginx版本隱藏才能實現預期效果
[root@CentOS7 nginx-1.14.2]#vim src/http/ngx_http_header_filter_module.c
 49 static u_char ngx_http_server_string[] = "Server: Darius/10.0" CRLF;

# 中止Nginx服務,從新編譯Nginx
[root@CentOS7 nginx-1.14.2]#/apps/nginx/sbin/nginx -s stop
[root@CentOS7 nginx-1.14.2]#./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/root/echo-nginx-module

[root@CentOS7 nginx-1.14.2]#make && make ×××tall

啓動服務
[root@CentOS7 nginx-1.14.2]#/apps/nginx/sbin/nginx

檢測
[root@CentOS7-Test ~]#curl -I www.darius.com
HTTP/1.1 200 OK
Server: Darius/10.0

# 修改src/core/nginx.h文件無需開啓隱藏功能,起到修改版本信息的效果
[root@CentOS7 nginx-1.14.2]# vim src/core/nginx.h
 13 #define NGINX_VERSION      "10.0"
 14 #define NGINX_VER          "Darius/" NGINX_VERSION

Nginx高階用法(二)

Nginx Rewrite相關功能

Nginx服務器利用ngx_http_rewrite_module 模塊解析和處理rewrite請求,此功能依靠 PCRE(perl compatibler egularexpression),所以編譯以前要安裝PCRE庫,rewrite是nginx服務器的重要功能之一,用於實現URL的重寫,URL的重寫是很是有用的功能,好比它能夠在咱們改變網站結構以後,不須要客戶端修改原來的書籤,也無需其餘網站修改咱們的連接,就能夠設置爲訪問,另外還能夠在必定程度上提升網站的安全性。nginx

if指令

用於條件匹配判斷,並根據條件判斷結果選擇不一樣的Nginx配置,能夠配置在server或location塊中進行配置,Nginx的if語法僅能使用if作單次判斷,不支持使用if else或者if elif這樣的多重判斷web

location /main {
    index index.html;
    default_type text/html;
    if ( $scheme = http ) {
      echo "if --> $scheme";
  }
  }
[root@CentOS7 conf.d]#nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntaxis ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@CentOS7 conf.d]#nginx -s reload

檢測
[root@CentOS7-Test ~]#curl www.darius.com/main
if --> http

使用正則表達式對變量進行匹配,匹配成功時if指令認爲條件爲true,不然認爲false,變量與表達式之間使用如下符號連接

=: #比較變量和字符串是否相等,相等時if指令認爲該條件爲true,反之爲false。
!=: #比較變量和字符串是否不相等,不相等時if指令認爲條件爲true,反之爲false。
~: #表示在匹配過程當中區分大小寫字符,(能夠經過正則表達式匹配),知足匹配條件爲真,不知足爲假。
~*: #表示在匹配過程當中不區分大小寫字符,(能夠經過正則表達式匹配),知足匹配條件爲真,不知足問假。
!~:#區分大小寫不匹配,不知足爲真,知足爲假,不知足爲真。
!~*:#爲不區分大小寫不匹配,知足爲假,不知足爲真。

-f 和 ! -f:判斷請求的文件是否存在和是否不存在
-d 和 ! -d: #判斷請求的目錄是否存在和是否不存在。
-x 和 ! -x: #判斷文件是否可執行和是否不可執行。
-e 和 ! -e: #判斷請求的文件或目錄是否存在和是否不存在(包括文件,目錄,軟連接)。

注: 若是$變量的值爲空字符串或是以0開頭的任意字符串,則if指令認爲該條件爲false,其餘條件爲true。

set指令

指定key並給其定義一個變量,變量能夠調用Nginx內置變量賦值給key,另外set定義格式爲set $key $value,及不管是key仍是value都要加$符號。正則表達式

[root@CentOS7 conf.d]#vim pc.conf
  location /set {
    root index.html;
    default_type text/html;
    set $name Darius;
    echo $name;
    set $my_port $server_port;
    echo $my_port;
  }

[root@CentOS7 conf.d]#nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntaxis ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@CentOS7 conf.d]#nginx -s reload

檢測
[root@CentOS7-Test ~]#curl www.darius.com/set
Darius
80

break指令

用於中斷當前相同做用域(location)中的其餘Nginx配置,與該指令處於同一做用域的Nginx配置中,位於它前面的配置生效,位於後面的指令配置就再也不生效了,Nginx服務器在根據配置處理請求的過程當中遇到該指令的時候,回到上一層做用域繼續向下讀取配置,該指令能夠在server塊和location塊以及if塊中使用,使用語法以下:express

[root@CentOS7 conf.d]#vim pc.conf
  location /set {
    root index.html;
    default_type text/html;
    set $name Darius;
    echo $name;
    break;
    set $my_port $server_port;
    echo $my_port;
  }

[root@CentOS7 conf.d]#nginx -s reload

檢測
[root@CentOS7-Test ~]#curl www.darius.com/set
Darius

return指令

從nginx版本0.8.2開始支持,return用於完成對請求的處理,並直接向客戶端返回響應狀態碼,好比其能夠指定重定向URL(對於特殊重定向狀態碼,301/302等) 或者是指定提示文本內容(對於特殊狀態碼403/500等),處於此指令後的全部配置都將不被執行,return能夠在server、if和location塊進行配置json

location /main {
    index index.html;
    default_type text/html;
    if ( $scheme = http ) {
      return 666 "not allow http"; # 能夠是返回給客戶端指定的HTTP狀態碼、也能夠是返回給客戶端的狀態碼及響應體內容(能夠調用變量)、或者返回給客戶端URL地址
      # echo "if-----> $scheme";  # return後面的將再也不執行
  }

[root@CentOS7-Test ~]#curl www.darius.com/main
not allow http
[root@CentOS7-Test ~]#curl -I www.darius.com/main
HTTP/1.1 666
Server: Darius/10.0
Date: Sat, 01 Jun 2019 03:52:37 GMT
Content-Type: text/html
Content-Length: 14
Connection: keep-alive

rewrite_log指令

設置是否開啓記錄ngx_http_rewrite_module模塊日誌記錄到error_log日誌文件當中,能夠配置在http、server、location或if當中,須要日誌級別爲noticevim

[root@CentOS7 conf.d]#vim ../conf/nginx.conf
error_log  logs/error.log  notice;  # 開啓錯誤日誌notice級別

[root@CentOS7 conf.d]#vim pc.conf  # 啓用rewrite_log指令
  location /set {
    root index.html;
    default_type text/html;
    set $name Darius;
    echo $name;
    rewrite_log on;
    break;
    set $my_port $server_port;
    echo $my_port;
  }

[root@CentOS7 conf.d]#nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@CentOS7 conf.d]#nginx -s reload

訪問並驗證
[root@CentOS7 conf.d]#tail -f /apps/nginx/logs/*.log
==> /apps/nginx/logs/error.log <==
2019/06/01 12:01:46 [warn] 11234#0: *40 using uninitialized "my_port" variable, client: 192.168.36.110, server: www.darius.com, request: "GET /set/aaa HTTP/1.1", host: "www.darius.com"

rewrite指令

經過正則表達式的匹配來改變URI,能夠同時存在一個或多個指令,按照順序依次對URI進行匹配,rewrite主要是針對用戶請求的URL或者是URI作具體處理 api

  URI(universal resource identifier):通用資源標識符,標識一個資源的路徑,能夠不帶協議。
  URL(uniform resource location):統一資源定位符,是用於在Internet中描述資源的字符串,是URI的子集,主要包括傳輸協議(scheme)、主機(IP、端口號或者域名)和資源具體地址(目錄和文件名)等三部分,通常格式爲 scheme://主機名[:端口號][/資源路徑],如:http://www.a.com:8080/path/file/index.html就是一個URL路徑,URL必須帶訪問協議
每一個URL都是一個URI,可是URI不都是URL。
  例如:
  http://example.org/path/to/resource.txt #URI/URL
  ftp://example.org/resource.txt #URI/URL
  /absolute/path/to/resource.txt #URI 瀏覽器

rewrite 四種flag使用介紹

  1. redirect;
      # 臨時重定向,重寫完成後以臨時重定向方式直接返回重寫後生成的新URL給客戶端,由客戶端從新發起請求;使用相對路徑,或者http://或https://開頭,狀態碼:302
  2. permanent;
      # 永久重定向,重寫完成後以永久重定向方式直接返回重寫後生成的新URL給客戶端,由客戶端從新發起請求,狀態碼:301
  3. last;
      # 重寫完成後中止對當前URI在當前location中後續的其它重寫操做,然後對新的URL啓動新一輪重寫檢查,不建議在location中使用
  4. break;
      # 重寫完成後中止對當前URL在當前location中後續的其它重寫操做,然後直接跳轉至重寫規則配置塊以後的其它配置;結束循環,建議在location中使用
注:其中前兩種是跳轉型的flag,後兩種是代理型,跳轉型是指有客戶端瀏覽器從新對新地址進行請求,代理型是在WEB服務器內部實現跳轉的。

rewrite域名永久重定向

[root@CentOS7 conf.d]#vim ../conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
            rewrite / http://www.darius.com permanent;  # 永久重定向301
            #rewrite / http://www.darius.com redirect;  # 臨時重定向302
        }

[root@CentOS7 conf.d]#nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@CentOS7 conf.d]#nginx -s reload

重定向檢測
[root@CentOS7-Test ~]#curl 192.168.36.104
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
[root@CentOS7-Test ~]#curl -L 192.168.36.104
www.darius.com
[root@CentOS7-Test ~]#curl -I 192.168.36.104
HTTP/1.1 301 Moved Permanently
Server: Darius/10.0
Date: Sat, 01 Jun 2019 04:27:42 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://www.darius.com

Nginx高階用法(二)

rewrite 臨時重定向

[root@CentOS7-Test ~]#curl -I 192.168.36.104
HTTP/1.1 302 Moved Temporarily
Server: Darius/10.0
Date: Sat, 01 Jun 2019 04:28:32 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: http://www.darius.com

Nginx高階用法(二)

rewrite之URI重定向

location /last {
    rewrite ^/last/(.*) /test$1 last;
    return 888 "last";
  }
  location /break {
    rewrite ^/break/(.*) /test$1 break;
    return 666 "break";
  }
  location /test {
    return 999 "test";
  }

[root@CentOS7 conf.d]#nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@CentOS7 conf.d]#nginx -s reload

# break不會跳轉到其餘location中
[root@CentOS7-Test ~]#curl -L -i http://www.darius.com/break/index.html
HTTP/1.1 404 Not Found
Server: Darius/10.0
Date: Sat, 01 Jun 2019 06:12:04 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
Vary: Accept-Encoding

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

# last會跳轉到其餘location中繼續執行匹配操做
[root@CentOS7-Test ~]#curl -L -i http://www.darius.com/last/index.html
HTTP/1.1 999
Server: Darius/10.0
Date: Sat, 01 Jun 2019 06:12:11 GMT
Content-Type: text/html
Content-Length: 4
Connection: keep-alive

test

rewrite實現頁面自動跳轉https

server {
  listen 80;
  listen 443 ssl;
  server_name www.darius.com;
  error_log /apps/nginx/logs/www_darius_com_error.log;
  access_log /apps/nginx/logs/www_darius_com_access.log access_json;
  ssl_certificate /apps/nginx/certs/www.darius.com.crt;
  ssl_certificate_key /apps/nginx/certs/www.darius.com.key;
  ssl_session_cache shared:sslcache:20m;
  ssl_session_timeout 10m;
  location / {
    root /data/nginx/html/pc;
    index index.html;
    if ( $scheme = http ){
      rewrite (.*) https://www.darius.com;
    }
  }
}
[root@CentOS7 conf.d]#nginx -s reload

訪問測試
[root@CentOS7-Test ~]#curl -L -i -k http://www.darius.com
HTTP/1.1 302 Moved Temporarily
Server: Darius/10.0
Date: Sat, 01 Jun 2019 06:29:34 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: https://www.darius.com

HTTP/1.1 200 OK
Server: Darius/10.0
Date: Sat, 01 Jun 2019 06:29:37 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 30 May 2019 03:06:03 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: "5cef489b-7"
Accept-Ranges: bytes

pc web

Nginx高階用法(二)

判斷文件是否存在

# 當用戶訪問到公司網站時,輸入一個錯誤的URL,能夠將用戶訪問的瀏覽頁面重定向到公司官網首頁上  
  location / {
    root /data/nginx/html/pc;
    index index.html;
    if ( !-f $request_filename ){
      rewrite (.*) http://www.darius.com/index.html;
    }
  }

瀏覽測試
[root@CentOS7-Test ~]#curl -L -i http://www.darius.com/asdfg
HTTP/1.1 302 Moved Temporarily
Server: Darius/10.0
Date: Sat, 01 Jun 2019 06:56:26 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: http://www.darius.com/index.html

HTTP/1.1 200 OK
Server: Darius/10.0
Date: Sat, 01 Jun 2019 06:56:26 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 30 May 2019 03:06:03 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: "5cef489b-7"
Accept-Ranges: bytes

pc web

Nginx防盜鏈

防盜鏈基於客戶端攜帶的referer實現,referer是記錄打開一個頁面以前記錄是從哪一個頁面跳轉過來的標記信息,若是別人只連接了本身網站圖片或某個單獨的資源,而不是打開了網站的整個頁面,這就是盜鏈,referer就是以前的那個網站域名,正常的referer信息有如下幾種:安全

none:請求報文首部沒有referer首部,好比用戶直接在瀏覽器輸入域名訪問web網站,就沒有referer信息。
blocked:請求報文有referer首部,但無有效值,好比爲空。
server_names:referer首部中包含本主機名及即nginx 監聽的server_name。
arbitrary_string:自定義指定字符串,但可以使用*做通配符。
regular expression:被指定的正則表達式模式匹配到的字符串,要使用~開頭,例如:
    ~.*\.magedu\.com。

盜鏈測試

Nginx高階用法(二)

[root@CentOS7 conf.d]#cat a.conf
server {
  listen 80;
  charset utf-8;
  server_name www.a.com;
  location / {
    root /data;
    index index.html;
  }
}
[root@CentOS7 conf.d]#cat /data/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盜鏈頁面</title>
</head>
<body>
<a href="http://www.darius.com">測試盜鏈</a>
<img src="http://www.darius.com/logo.png">
</body>
</html>

Nginx高階用法(二)

被盜鏈日誌查看

[root@CentOS7 conf.d]#tail -f /apps/nginx/logs/*.log
==> /apps/nginx/logs/www_darius_com_access.log <==
{"@timestamp":"2019-06-01T15:21:30+08:00","host":"192.168.36.104","clientip":"192.168.36.1","size":0,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-","http_host":"www.darius.com","uri":"/logo.png","domain":"www.darius.com","xff":"-","referer":"http://www.a.com/","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0","status":"304"}

開啓防盜鏈機制

基於訪問安全考慮,nginx支持經過ungx_http_referer_module模塊檢查訪問請求的referer信息是否有效實現防盜鏈功能

location / {
    root /data/nginx/html/pc;
    index index.html;
    valid_referers none blocked server_names *.magedu.com www.magedu.* api.online.test/v1/hostlist ~\.google\. ~\.baidu\.;
    if ($invalid_referer) {
      return 403;
    }
  }
[root@CentOS7 conf.d]#nginx -s reload

頁面訪問測試
Nginx高階用法(二)

相關文章
相關標籤/搜索