Nginx高階用法(二)

關於favicon.ico

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

具體配置

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

顯示效果

Nginx高階用法(二)

修改Nginx Server版本信息

# 修改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 install

啓動服務
[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

Nginx高階用法(二)

Nginx Rewrite相關功能

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

if指令

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

  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塊中使用,使用語法如下:

[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塊進行配置

  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當中,需要日誌級別爲notice

[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做具體處理

  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高階用法(二)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章