linxu nginx非常詳細--yum安裝 編譯安裝 模塊安裝 日志格式

Http

Http協議介紹

超文本傳輸協議(Hypertext Transfer Protocol,HTTP)是一個用于傳輸超媒體文檔(例如 HTML)的應用層協議。它是為 Web 瀏覽器與 Web 服務器之間的通信而設計的,但也可以用于其他目的。HTTP 遵循經典的客戶端-服務端模型,客戶端打開一個連接以發出請求,然后等待直到收到服務器端響應。HTTP 是無狀態協議,這意味著服務器不會在兩個請求之間保留任何數據(狀態)。盡管通常基于 TCP/IP 層,但它可以在任何可靠的傳輸層上使用,也就是說,該協議不會像 UDP 那樣靜默的丟失消息。RUDP——作為 UDP 的可靠化升級版本——是一種合適的替代選擇。

http版本

http1.0 短鏈接 鏈接 請求 響應 斷開

http1.1 長鏈接 連接 請求 響應 請求 響應 請求 響應 斷開

http2 流水線 連接 請求 請求 請求 響應 響應 響應 斷開

img

詳細介紹 點我

統一資源定位符 (URL)

方案或協議

img

http://告訴瀏覽器使用何種協議。對于大部分 Web 資源,通常使用 HTTP 協議或其安全版本,HTTPS 協議。另外,瀏覽器也知道如何處理其他協議。例如, mailto: 協議指示瀏覽器打開郵件客戶端;ftp:協議指示瀏覽器處理文件傳輸。常見的方案有:

主機

img

www.example.com 既是一個域名,也代表管理該域名的機構。它指示了需要向網絡上的哪一臺主機發起請求。當然,也可以直接向主機的 IP address 地址發起請求。但直接使用 IP 地址的場景并不常見。

端口

img

:80 是端口。它表示用于訪問 Web 服務器上資源的技術“門”。如果訪問的該 Web 服務器使用HTTP協議的標準端口(HTTP為80,HTTPS為443)授予對其資源的訪問權限,則通常省略此部分。否則端口就是 URI 必須的部分。

路徑

img

/path/to/myfile.html 是 Web 服務器上資源的路徑。在 Web 的早期,類似這樣的路徑表示 Web 服務器上的物理文件位置。現在,它主要是由沒有任何物理實體的 Web 服務器抽象處理而成的。

查詢

img

?key1=value1&key2=value2 是提供給 Web 服務器的額外參數。這些參數是用 & 符號分隔的鍵/值對列表。Web 服務器可以在將資源返回給用戶之前使用這些參數來執行額外的操作。每個 Web 服務器都有自己的參數規則,想知道特定 Web 服務器如何處理參數的唯一可靠方法是詢問該 Web 服務器所有者。

片段

img

#SomewhereInTheDocument 是資源本身的某一部分的一個錨點。錨點代表資源內的一種“書簽”,它給予瀏覽器顯示位于該“加書簽”點的內容的指示。 例如,在HTML文檔上,瀏覽器將滾動到定義錨點的那個點上;在視頻或音頻文檔上,瀏覽器將轉到錨點代表的那個時間。值得注意的是 # 號后面的部分,也稱為片段標識符,永遠不會與請求一起發送到服務器。

訪問網站分析

  1. 瀏覽器分析超鏈接中的URL

  2. 瀏覽器向DNS請求解析網址的IP地址

  3. DNS將解析出的IP地址返回瀏覽器

  4. 瀏覽器與服務器建立TCP連接(80端口)

  5. 瀏覽器請求文檔: GET /index.htmI

  6. 服務器給出響應,將文檔index.html發送給瀏覽器

  7. 瀏覽器顯示index.html中的內容

  8. 釋放TCP連接

先連接 后請求

Http請求(request)方法

方法(Method)是對所請求對象所進行的操作,也就是一些命令。 請求報文中的操作有:

img

消息頭

img

cookies

HTTP Cookie(也叫 Web Cookie 或瀏覽器 Cookie)是服務器發送到用戶瀏覽器并保存在本地的一小塊數據,它會在瀏覽器下次向同一服務器再發起請求時被攜帶并發送到服務器上。通常,它用于告知服務端兩個請求是否來自同一瀏覽器,如保持用戶的登錄狀態。Cookie 使基于無狀態的HTTP協議記錄穩定的狀態信息成為了可能。

Cookie 主要用于以下三個方面:

  • 會話狀態管理(如用戶登錄狀態、購物車、游戲分數或其它需要記錄的信息)

  • 個性化設置(如用戶自定義設置、主題等)

  • 瀏覽器行為跟蹤(如跟蹤分析用戶行為等)

詳見鏈接

Http響應(response)方法

響應報文中的狀態碼

狀態碼(Status-Code)是響應報文狀態行中包含的一個3位數字,指明特定的請求是否被滿足,如果沒有滿足,原因是什么。狀態碼分為以下五類:

img
200     # 成功請求
301     # 永久重定向(redirect) 客戶端請求的網頁已經永久移動到新的位置,當鏈接發生變化時,返回301代碼告訴客戶端鏈接的變化,客戶端保存新的鏈接,并向新的鏈接發出請求,已返回請求結果
302     # 臨時重定向(redirect) http--->https
304     # 瀏覽器緩存
403     # 請求不到首頁或權限被拒絕
404     # 請求的資源不存在
500     # 服務器內部錯誤,程序代碼錯誤
502     # 找不到后端的資源
503     # 服務器由于臨時的服務器過載或者是維護,無法解決當前的請求
504     # 請求超時

消息頭

img

Http相關術語

PV(Page View)

訪問量, 即頁面瀏覽量或點擊量,衡量網站用戶訪問的網頁數量;在一定統計周期內用戶每打開或刷新一個頁面就記錄1次,多次打開或刷新同一頁面則瀏覽量累計。

UV(Unique Visitor)

獨立訪客,統計1天內訪問某站點的用戶數(以cookie為依據);訪問網站的一臺電腦客戶端為一個訪客。

IP(Internet Protocol)

獨立IP數,是指1天內多少個獨立的IP瀏覽了頁面,即統計不同的IP瀏覽用戶數量。同一IP不管訪問了幾個頁面,獨立IP數均為1;不同的IP瀏覽頁面,計數會加1。 IP是基于用戶廣域網IP地址來區分不同的訪問者的,所以,多個用戶(多個局域網IP)在同一個路由器(同一個廣域網IP)內上網,可能被記錄為一個獨立IP訪問者。如果用戶不斷更換IP,則有可能被多次統計。

SOA松耦合架構

面向服務的架構(SOA)是一個組件模型,它將應用程序的不同功能單元(稱為服務)進行拆分,并通過這些服務之間定義良好的接口和協議聯系起來。接口是采用中立的方式進行定義的,它應該獨立于實現服務的硬件平臺、操作系統和編程語言。這使得構建在各種各樣的系統中的服務可以以一種統一和通用的方式進行交互。

Nginx基礎

Nginx是一個開源且高性能、可靠的Http Web服務、代理服務。

開源: 直接獲取源代碼高性能: 支持海量并發可靠: 服務穩定

Nginx的優勢

Nginx非常輕量

功能模塊少 (源代碼僅保留http與核心模塊代碼,其余不夠核心代碼會作為插件來安裝)

代碼模塊化 (易讀,便于二次開發,對于開發人員非常友好)

互聯網公司都選擇Nginx

1.Nginx技術成熟,具備的功能是企業最常使用而且最需要的

2.適合當前主流架構趨勢, 微服務、云架構、中間層

3.統一技術棧, 降低維護成本, 降低技術更新成本。

Nginx采用Epool網絡模型,Apache采用Select模型

Select: 當用戶發起一次請求,select模型就會進行一次遍歷掃描,從而導致性能低下。

Epool: 當用戶發起請求,epool模型會直接進行處理,效率高效,并無連接限制。

應用場景廣泛

開源的web服務器

靜態資源

nginx` `apache` `IIS` `lighttpd` `tengine` `openresty

動態

Tomcat  java` `Jboos

tomcat 處理動態資源強大 靜態不行 所以一般和nginx配合使用

Nginx快速安裝

Nginx軟件安裝的方式有很多種

1.源碼編譯=>Nginx (1.版本隨意 2.安裝復雜 3.升級繁瑣)

2.epel倉庫=>Nginx (1.版本較低 2.安裝簡單 3.配置不易讀)

3.官方倉庫=>Nginx (1.版本較新 2.安裝簡單 3.配置易讀,推薦)

yum安裝

1.安裝Nginx軟件所需依賴包

yum install -y gcc gcc-c++ autoconf pcre pcre-devel make automake wget httpd-tools vim tree make pcre-devel zlib-devel openssl-devel pcre-devel

2.配置nginx官方 yum源

# vim /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

3.安裝Nginx服務,啟動并加入開機自啟

[root@web ~]# yum install nginx -y
[root@web ~]# systemctl enable nginx
[root@web ~]# systemctl start nginx

4.檢查Nginx軟件版本以及編譯參數

[root@web ~]# nginx -v
nginx version: nginx/1.14.0
[root@web ~]# nginx -V # 查看nginx的編譯參數

編譯安裝

下載nginx源碼包并解壓

可在http://nginx.org/en/download.html下載.tar.gz的源碼包,如(nginx-1.4.7.tar.gz)

下載后通過tar -xvzf 進行解壓,解壓后的nginx目錄結構如下:

img

為nginx設置安裝目錄和啟用的模塊

切換到解壓后的nginx目錄中執行:

./configure --prefix=/opt/demo/nginx --add-module=/home/fastdfs-nginx-module/src --with-http_stub_status_module --with-http_ssl_module

注: 這里可以使用nginx -V查看別的已經安裝的nginx的參數 別的自己需要什么添加什么參數

參數說明:

--prefix 用于指定nginx編譯后的安裝目錄
--add-module 為添加的第三方模塊,此次添加了fdfs的nginx模塊
--with..._module 表示啟用的nginx模塊,如此處啟用了http_ssl_module模塊
--user=nginx (指定運行用戶和組)
--group=nginx(指定運行用戶和組)
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_gzip_static_module
--with-http_stub_status_module(啟用該模塊以支持狀態統計)
--with-http_ssl_module(啟用SSL模塊)
--with-http_flv_module(啟用FLV模塊,提供尋求內存使用基于時間的偏移量文件)
--with-http_gzip_static_module(預讀gzip功能)

可能出現的錯誤:

出現:./configure: error: the HTTP rewrite module requires the PCRE library.

解決方法:yum -y install pcre-devel

出現:SSL modules require the OpenSSL library

解決方法:yum install openssl-devel

編譯

執行make 進行編譯,如果編譯成功的話會在第一步中objs中出現一個nginx文件

特別注意:

在已安裝的nginx上進行添加模塊的話執行到這里就行了,把objs中的nginx替換掉之前的安裝的nginx/sbin/中的nginx文件,然后重啟nginx就行了,如果執行下一步的install,會導致之前安裝的nginx被覆蓋,比如之前配置好的nginx.conf文件)

安裝

執行make install 進行安裝,安裝后--prefix 中指定的安裝目錄下回出現如下目錄結構

啟動nginx

切入到第四步中的sbin目錄或是創建一個nginx軟鏈接

ln -s /opt/demo/nginx/sbin/nginx /usr/bin/nginx

完成后執行:

nginx start(如需開機自啟,可在/etc/rc.d/rc.local 文件中添此命令)

如出現:nginx: [error] invalid PID number "" in "/usr/local/nginx/logs/nginx.pid"

則需通過nginx –c ../conf/nginx.conf 命令指定nginx的配置

nginx配置文件

為了讓大家更清晰的了解Nginx軟件的全貌,可使用rpm -ql nginx查看整體的目錄結構及對應的功能,如下表格整理了Nginx比較重要的配置文件

1.Nginx主配置文件

路徑 類型 作用
/etc/nginx/nginx.conf 配置文件 nginx主配置文件
/etc/nginx/conf.d/default.conf 配置文件 默認網站配置文件

2.Nginx代理相關參數文件

路徑 類型 作用
/etc/nginx/fastcgi_params 配置文件 Fastcgi代理配置文件
/etc/nginx/scgi_params 配置文件 scgi代理配置文件
/etc/nginx/uwsgi_params 配置文件 uwsgi代理配置文件

3.Nginx編碼相關配置文件

路徑 類型 作用
/etc/nginx/win-utf 配置文件 Nginx編碼轉換映射文件
/etc/nginx/koi-utf 配置文件 Nginx編碼轉換映射文件
/etc/nginx/koi-win 配置文件 Nginx編碼轉換映射文件
/etc/nginx/mime.types 配置文件 Content-Type與擴展名

4.Nginx管理相關命令

路徑 類型 作用
/usr/sbin/nginx 命令 Nginx命令行管理終端工具
/usr/sbin/nginx-debug 命令 Nginx命令行與終端調試工具

4.Nginx日志相關目錄與文件

路徑 類型 作用
/var/log/nginx 目錄 Nginx默認存放日志目錄
/etc/logrotate.d/nginx 配置文件 Nginx默認的日志切割

默認配置

Nginx主配置文件/etc/nginx/nginx.conf是一個純文本類型的文件,整個配置文件是以區塊的形式組織的。一般,每個區塊以一對大括號{}來表示開始與結束。
Nginx主配置文件整體分為三塊進行學習,分別是CoreModule(核心模塊),EventModule(事件驅動模塊),HttpCoreModule(http內核模塊)

CoreModule核心模塊

user www;                       #Nginx進程所使用的用戶
worker_processes 1;             #Nginx運行的work進程數量(建議與CPU數量一致或auto)
error_log /log/nginx/error.log  #Nginx錯誤日志存放路徑
pid /var/run/nginx.pid          #Nginx服務運行后產生的pid進程號

events事件模塊

events {            
    worker_connections 25535;  #每個worker進程支持的最大連接數
    use epoll;                  #事件驅動模型, epoll默認
}

http內核模塊

http {  #http層開始
...    
    #使用Server配置網站, 每個Server{}代表一個網站(簡稱虛擬主機)
    'server' {
        listen       80;            #監聽端口, 默認80
        server_name  www.baidu.com;       #提供的域名
        access_log  access.log;     #該網站的訪問日志
        #控制網站訪問路徑
        'location' / {
            root   /usr/share/nginx/html;   #存放網站源代碼的位置 #這里可以是root也可以是alias 如果是root 那么找的就是
            index  index.html index.htm;    #默認返回網站的文件
        }
    }
    ...
    #第二個虛擬主機配置
    'server' {
    ...
    }
    
    include /etc/nginx/conf.d/*.conf;  #包含/etc/nginx/conf.d/目錄下所有以.conf結尾的文件
}   #http層結束

http server location擴展了解項

  • http{}層下允許有多個Server{}層,一個Server{}層下又允許有多個Location

  • http{} 標簽主要用來解決用戶的請求與響應。

  • server{} 標簽主要用來響應具體的某一個網站。

  • location{} 標簽主要用于匹配網站具體URL路徑。

root與alias的區別

格式

nginx指定文件路徑有兩種方式root和alias,指令的使用方法和作用域:

[root]

語法:root path

默認值:root html

配置段:http、server、location、if

[alias]

語法:alias path

配置段:location

root與alias主要區別

在于nginx如何解釋location后面的uri,這會使兩者分別以不同的方式將請求映射到服務器文件上。

root的處理結果是:root路徑 + location路徑

alias的處理結果是:使用alias路徑替換location路徑

alias是一個目錄別名的定義,root則是最上層目錄的定義。

還有一個重要的區別是alias后面必須要用“/”結束,否則會找不到文件的,而root則可有可無。

例:

# 如果一個請求的URI是/t/a.html時,web服務器將會返回服務器上的/www/root/html/t/a.html的文件。
location ^~ /t/ {
    root /www/root/html/;
}
# 如果一個請求的URI是/t/a.html時,web服務器將會返回服務器上的/www/root/html/new_t/a.html的文件。
# 注意這里是new_t,因為alias會把location后面配置的路徑丟棄掉,把當前匹配到的目錄指向到指定的目錄。
location ^~ /t/ {
    alias /www/root/html/new_t/;
}
  • 使用alias時,目錄名后面一定要加"/"。

  • alias在使用正則匹配時,必須捕捉要匹配的內容并在指定的內容處使用。

  • alias只能位于location塊中。(root可以不放在location中)

Nginx網站配置

1.新增nginx配置文件

[root@web01 conf.d]# cat /etc/nginx/conf.d/game.conf 
server {
    listen 80;
    server_name game.baidu.com;
    location / {
        root /code;
        index index.html;
    }
}

2.放置源代碼文件至nginx配置文件root指定的目錄

[root@web01 conf.d]# mkdir /code && cd /code
[root@web01 code]# rz  html5.zip
[root@web01 code]# unzip html5.zip
[root@web01 code]# ls
ceshi  game  html5.zip  img  index.html  readme.txt

3.檢查nginx的語法是否存在錯誤

[root@web01 code]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

4.重載Nginx [reload|restart]

[root@web01 code]# systemctl reload nginx

reload和restart的區別

reload 平滑重啟 等連接斷開后重啟

restart 強制重啟 強制斷開連接

Nginx虛擬主機

通常在企業中可能會有很多業務系統,那么多套業務服務如何使用Nginx配置?

如果使用如上方式部署,則需要多臺服務器配置Nginx,但如果使用虛擬主機方式,則在同一個Nginx上運行多套單獨服務,這些服務是相互獨立的。簡單來說,看似多套業務系統,實則可以運行在一臺Nginx服務上

Nginx配置虛擬主機有如下三種方式:

方式一、基于主機多IP方式
方式二、基于端口的配置方式
方式三、基于多個hosts名稱方式(多域名方式)

基于多IP的虛擬主機配置實戰

那么基于多IP的方式,有如下兩種方式:

1.配置多網卡多IP的方式

server {
    ...
    listen 10.0.0.10:80;
    ...
}
server {
    ...
    listen 10.0.0.11:80;
    ...
}

1.配置單網卡多IP的方式

#添加一個IP
[root@web01 ~]# ip addr add 10.0.0.11/24 dev eth0
# 虛擬機配置方案
[root@web01 ~]# cat /etc/nginx/conf.d/addr1.conf
server {
    ...
    listen 10.0.0.10:80;
    ...
}
[root@web01 ~]# cat /etc/nginx/conf.d/addr2.conf
server {
    ...
    listen 10.0.0.11:80;
    ...
}

基于端口虛擬主機配置實戰

Nginx多端口虛擬主機方式,具體配置如下

#僅修改listen監聽端口即可, 但不能和系統端口出現沖突
[root@web01 ~]# cat /etc/nginx/conf.d/port1.conf
server {
    ...
    listen 80;
    ...
}
[root@web01 ~]# cat /etc/nginx/conf.d/port2.conf
server {
    ...
    listen 81;
    ...
}
[root@web01 ~]# cat /etc/nginx/conf.d/port3.conf
server {
    ...
    listen 82;
    ...
}

基于host名稱的虛擬主機方式配置實戰

1.創建對應的web站點目錄以及程序代碼

[root@web01 ~]# mkdir /soft/code/{server1,server2}
[root@web01 ~]# echo "server1" > /code/server1/index.html
[root@web01 ~]# echo "server2" > /code/server2/index.html

2.配置不同域名的虛擬主機

[root@web02 ~]# cat /etc/nginx/conf.d/server1.conf
server {
    listen       80;
    server_name  1.baidu.com;
    root /code/server1;
    index index.html;
    ...
}
[root@web01 ~]# cat /etc/nginx/conf.d/server2.conf
server {
    ...
    listen       80;
    server_name  2.baidu.com;
    root /code/server2;
    index index.html;
}

Nginx日志管理

Nginx有非常靈活的日志記錄模式,每個級別的配置可以有各自獨立的訪問日志。日志格式通過log_format命令定義格式。

1.log_format定義日志格式語法

# 配置語法: 包括: error.log access.log
Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http

2.默認Nginx定義語法格式如下

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

3.Nginx日志格式允許包含的內置變量

$remote_addr        # 記錄客戶端IP地址
$remote_user        # 記錄客戶端用戶名
$time_local         # 記錄通用的本地時間
$time_iso8601       # 記錄ISO8601標準格式下的本地時間
$request            # 記錄請求的方法以及請求的http協議
$status             # 記錄請求狀態碼(用于定位錯誤信息)
$body_bytes_sent    # 發送給客戶端的資源字節數,不包括響應頭的大小
$bytes_sent         # 發送給客戶端的總字節數
$msec               # 日志寫入時間。單位為秒,精度是毫秒。
$http_referer       # 記錄從哪個頁面鏈接訪問過來的
$http_user_agent    # 記錄客戶端瀏覽器相關信息
$http_x_forwarded_for #記錄客戶端IP地址
$request_length     # 請求的長度(包括請求行, 請求頭和請求正文)。
$request_time       # 請求花費的時間,單位為秒,精度毫秒

# 注:如果Nginx位于負載均衡器,nginx反向代理之后, web服務器無法直接獲取到客 戶端真實的IP地址。
# $remote_addr獲取的是反向代理的IP地址。 反向代理服務器在轉發請求的http頭信息中,
# 增加X-Forwarded-For信息,用來記錄客戶端IP地址和客戶端請求的服務器地址。

4.access_log日志配置語法

Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default: access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except

5.Nginx Access日志配置實踐

server {
    listen 80;
    server_name code.baidu.com;
    
    #將當前的server網站的訪問日志記錄至對應的目錄,使用main格式
    access_log /var/log/nginx/code.baidu.com.log main;
    location / {
        root /code;
    }
    #當有人請求改favicon.ico時,不記錄日志
    location /favicon.ico {
        access_log off;
        return 200;
    }
}

日志切割logrotate

[root@nginx conf.d]# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
        daily                   # 每天切割日志
        missingok               # 日志丟失忽略
        rotate 52               # 日志保留52天
        compress                # 日志文件壓縮
        delaycompress           # 延遲壓縮日志
        notifempty              # 不切割空文件
        create 640 nginx adm    # 日志文件權限
        sharedscripts
        postrotate      # 切割日志執行的命令
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

Nginx模塊

模塊官網地址

Nginx目錄索引

ngx_http_autoindex_module

ngx_http_autoindex_module模塊處理以斜杠字符('/')結尾的請求,并生成目錄列表。
ngx_http_index_module模塊找不到索引文件時,通常會將請求傳遞給模塊。

1.指令

#啟用或禁用目錄列表輸出,on開啟,off關閉。
Syntax: autoindex on | off;
Default:    autoindex off;
Context:    http, server, location
#指定是否應在目錄列表中輸出確切的文件大小,on顯示字節,off顯示大概單位。
Syntax: autoindex_exact_size on | off;
Default: autoindex_exact_size on;
Context:    http, server, location
#指定目錄列表中的時間是應以本地時區還是UTC輸出。on本地時區,off UTC時間。
Syntax: autoindex_localtime on | off;
Default: autoindex_localtime off;
Context: http, server, location

2.示例配置

[root@web ~]# cat /etc/nginx/conf.d/module.conf 
server {
    listen 80;
    server_name module.baidu.com;
    charset utf-8,gbk;  #設定字符集,防止中文字符亂碼顯示。
    
    location /download {
        root /code/;
        autoindex on;
        autoindex_exact_size off;
    }
}

Nginx狀態監控

ngx_http_stub_status_module

ngx_http_stub_status_module模塊提供對基本狀態信息的訪問。
默認情況下不構建此模塊,應使用--with-http_stub_status_module配置參數啟用它 。

1.指令

Syntax: stub_status;
Default: —
Context: server, location

2.示例配置

[root@web ~]# cat /etc/nginx/conf.d/module.conf
server {
    listen 80;
    server_name module.bgx.com;
    access_log off;
    
    location /nginx_status {
        stub_status;
    }
}

3.此配置創建一個簡單的網頁,其基本狀態數據可能如下所示:

img

4.提供以下狀態信息

Active connections  # 當前活動客戶端連接數,包括Waiting等待連接數。
accepts             # 已接受總的TCP連接數。
handled             # 已處理總的TCP連接數。
requests            # 客戶端總的http請求數。
Reading             # 當前nginx讀取請求頭的連接數。
Writing             # 當前nginx將響應寫回客戶端的連接數。
Waiting             # 當前等待請求的空閑客戶端連接數。
# 注意, 一次TCP的連接,可以發起多次http的請求, 如下參數可配置進行驗證
keepalive_timeout  0;   # 類似于關閉長連接
keepalive_timeout  65;  # 65s沒有活動則斷開連接

Nginx訪問控制

ngx_http_access_module

ngx_http_access_module模塊允許限制對某些客戶端地址的訪問。

1.指令

#允許配置語法
Syntax: allow address | CIDR | unix: | all;
Default:    —
Context:    http, server, location, limit_except
#拒絕配置語法
Syntax: deny address | CIDR | unix: | all;
Default:    —
Context:    http, server, location, limit_except

2.示例配置,拒絕指定的IP訪問該網站的/nginx_status, 其他IP全部允許訪問

location /nginx_status {
  stub_status;
  #deny 192.168.5.4/32; #拒絕某個ip訪問其他的都可以訪問
  #allow all;
 
  allow 127.0.0.1; #監控nginx狀態時,僅允許該服務器的回環地址訪問
  deny all;
 }

3.示例配置,只允許指定的來源IP能訪問/nginx_status, 其它網段全部拒絕

[root@web ~]# cat /etc/nginx/conf.d/module.conf
server {
    listen 80;
    server_name module.bgx.com;
        
    location /nginx_status {
        stub_status;
        allow 127.0.0.1;  #監控nginx狀態時使用
        allow 10.0.0.1/32;  #允許地址或地址段
        deny all;              #拒絕所有人
    }
}

注意:deny和allow的順序是有影響的

  • 默認情況下,從第一條規則進行匹配

  • 如果匹配成功,則不繼續匹配下面的內容。

  • 如果匹配不成功,則繼續往下尋找能匹配成功的內容。

Nginx資源限制

ngx_http_auth_basic_module

ngx_http_auth_basic_module模塊允許使用HTTP基本身份驗證,驗證用戶名和密碼來限制對資源的訪問。

1.指令

#使用HTTP基本身份驗證協議啟用用戶名和密碼驗證。
Syntax: auth_basic string| off;
Default: auth_basic off;
Context: http, server, location, limit_except
#指定保存用戶名和密碼的文件
Syntax: auth_basic_user_file file;
Default: -
Context: http, server, location, limit_except

2.指定保存用戶名和密碼的文件,格式如下:

#可以使用htpasswd程序或"openssl passwd"命令生成對應的密碼;
name1:passwd1
name2:passwd2
#使用htpaaswd創建新的密碼文件, -c創建新文件 -b允許命令行輸入密碼
[root@xuliangwei ~]# yum install httpd-tools
[root@xuliangwei ~]# htpasswd -b -c /etc/nginx/auth_conf admin 123456 #這里如果不想留下history記錄 可以不使用-b

3.在conf中配置

auth_basic "what's your problem ?";
auth_basic_user_file /etc/nginx/auth_conf;

Nginx訪問限制

經常會遇到這種情況,服務器流量異常,負載過大等等。對于大流量惡意的攻擊訪問,會帶來帶寬的浪費,服務器壓力,從而影響業務,針對這種情況我們可以考慮對同一個ip的連接數,請求數、進行限制。

ngx_http_limit_conn_module

ngx_http_limit_conn_module模塊用于限制定義key的連接數,特別是來自單個IP地址的連接數。
但并非所有連接都被計算在內,僅當連接已經讀取了整個請求頭時才計算連接。

1.指令

Syntax:  limit_conn_zone key zone=name:size;
Default: —
Context: http
Syntax: limit_conn zone number;
Default: —
Context: http, server, location

2.設置共享內存區域和給定鍵值的最大允許連接數。超過此限制時,服務器將返回錯誤以回復請求

# http標簽段定義連接限制
http{
    limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
}
server {
    # 同一時刻只允許一個客戶端連接
    limit_conn conn_zone 1; 
    location / {
        root /code;
        index index.html;
    }

3).使用 ab 工具進行壓力測試

[root@xuliangwei ~]# yum install -y httpd-tools
[root@xuliangwei ~]# ab -n 20 -c 2  http://127.0.0.1/index.html

4).nginx日志結果

2018/10/24 18:04:49 [error] 28656#28656: *1148 limiting connections by zone "conn_zone", client: 123.66.146.123, server: www.xuliangwei.com, request: "GET / HTTP/1.0", host: "www.xuliangwei.com"
2018/10/24 18:04:49 [error] 28656#28656: *1155 limiting connections by zone "conn_zone", client: 123.66.146.123, server: www.xuliangwei.com, request: "GET / HTTP/1.0", host: "www.xuliangwei.com"

ngx_http_limit_req_module

ngx_http_limit_req_module模塊用于限制定義key請求的處理速率,特別單一的IP地址的請求的處理速率。

1.指令

#模塊名ngx_http_limit_req_module
Syntax:  limit_req_zone key zone=name:size rate=rate;
Default: —
Context: http
Syntax: limit_conn zone number [burst=number] [nodelay];
Default: —
Context: http, server, location

2.設置共享內存區域和請求的最大突發大小。過多的請求被延遲,直到它們的數量超過最大的限制,在這種情況下請求以錯誤終止。

# http標簽段定義請求限制, rate限制速率,限制一秒鐘最多一個IP請求
http {
    limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
}
server {
    listen 80;
    server_name module.bgx.com;
    # 1r/s只接收一個請求,其余請求拒絕處理并返回錯誤碼給客戶端
    #limit_req zone=req_zone;
    
    # 請求超過1r/s,剩下的將被延遲處理,請求數超過burst定義的數量, 多余的請求返回503 寫nodelay的話延時后面剩下的直接被拒絕
    limit_req zone=req_zone burst=3 nodelay;
    location / {
        root /code;
        index index.html;
    }
}

3).使用ab工具進行壓力測試

[root@xuliangwei ~]# yum install -y httpd-tools
[root@xuliangwei ~]# ab -n 500 -c 2  http://127.0.0.1/index.html

4).nginx日志結果

2018/10/24 07:38:53 [error] 81020#0: *8 limiting requests, excess: 3.998 by zone "req_zone", client: 10.0.0.10, server: module.bgx.com, request: "GET /index.html HTTP/1.0", host: "10.0.0.10"
2018/10/24 07:38:53 [error] 81020#0: *9 limiting requests, excess: 3.998 by zone "req_zone", client: 10.0.0.10, server: module.bgx.com, request: "GET /index.html HTTP/1.0", host: "10.0.0.10"

Nginx連接限制沒有請求限制有效?

我們先來回顧一下http協議的連接與請求,首先HTTP是建立在TCP基礎之上, 在完成HTTP請求需要先建立TCP三次握手(稱為TCP連接),在連接的基礎上在完成HTTP的請求。

所以多個HTTP請求可以建立在一次TCP連接之上, 那么我們對請求的精度限制,當然比對一個連接的限制會更加的有效,因為同一時刻只允許一個TCP連接進入, 但是同一時刻多個HTTP請求可以通過一個TCP連接進入。所以針對HTTP的請求限制才是比較優的解決方案。

Nginx Location

使用Nginx Location可以控制訪問網站的路徑, 但一個server允許出現多個location配置, 那多個location出現沖突誰的優先級會更高呢

1.Location語法示例

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

2.Location語法優先級排列

匹配符 匹配規則 優先級
= 精確匹配 1
^~ 以某個字符串開頭 2
~ 區分大小寫的正則匹配 3
~* 不區分大小寫的正則匹配 4
!~ 區分大小寫不匹配的正則 5
!~* 不區分大小寫不匹配的正則 6
/ 通用匹配,任何請求都會匹配到 7

3.配置網站驗證Location優先級

[root@Nginx conf.d]# cat testserver.conf 
server {
    listen 80;
    server_name module.baidu.com;
    location / {
        default_type text/html;
        return 200 "location /";
    }
    location =/ {
        default_type text/html;
        return 200 "location =/";
    }
    location ~ / {
        default_type text/html;
        return 200 "location ~/";
    }
    # location ^~ / {
    #   default_type text/html;
    #   return 200 "location ^~";
    # }
}

4.測試Location優先級

# 優先級最高符號=
[root@Nginx conf.d]# curl module.baidu.com
location =/
# 注釋掉精確匹配=, 重啟Nginx
[root@Nginx ~]# curl module.baidu.com
location ~/
# 注釋掉~, 重啟Nginx
[root@Nginx ~]# curl module.baidu.com
location /

5.Locaiton規則配置應用場景

# 通用匹配,任何請求都會匹配到
location / {
    ...
}
# 嚴格區分大小寫,匹配以.php結尾的都走這個location    
location ~ \.php$ {
    ...
}
# 嚴格區分大小寫,匹配以.jsp結尾的都走這個location 
location ~ \.jsp$ {
    ...
}
# 不區分大小寫匹配,只要用戶訪問.jpg,gif,png,js,css 都走這條location
location ~* .*\.(jpg|gif|png|js|css)$ {
    ...
}
# 不區分大小寫匹配
location ~* "\.(sql|bak|tgz|tar.gz|.git)$" {
    ...
}

nginx 安裝geoip

yum install nginx-module-geoip -y

nginx geoip_module模塊

ngx_http_geoip_module是對IP地址進行地域信息的讀取。客戶端在訪問時,通過ip地址能夠知道客戶端所在的國家,城市。常用于處理不同國家的客戶訪問。

1.下載nginx-module-geoip

在第3小節中記錄nginx安裝中,默認是沒有安裝這個模塊。需要手動下載ngx_http_geoip_module模塊。

yum install nginx-module-geoip

安裝成功后,會在/etc/nginx/module文件夾下出現geoip模塊。

2.安裝MaxMind的GeoIP庫

將GeoIP庫下載目錄/opt/download文件夾下

cd /opt/download  #如果沒有手動創建
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
tar -zxvf GeoIP.tar.gz
cd GeoIP-1.4.8
./configure
make
make install

剛才安裝的庫自動安裝到 /usr/local/lib 下,所以這個目錄需要加到動態鏈接配置里面以便運行相關程序的時候能自動綁定到這個 GeoIP 庫:

echo '/usr/local/lib' > /etc/ld.so.conf.d/geoip.conf
ldconfig

3.下載IP數據庫

最終目錄結構

/etc/nginx/data/geoip
|-GeoIP.dat
|-GeoLiteCity.dat

MaxMind 提供了免費的 IP 地域數據庫,這個數據庫是二進制的,不能用文本編輯器打開,需要上面的 GeoIP 庫來讀取。小菜在這里放一個官方的下載地址官方下載{:target="_blank"}
需要下載GeoIP.dat.gz文件和GeoLiteCity.dat.gz文件。小菜在這里放一個云盤,方便國內小伙伴獲取云盤地址{:target="_blank"} 提取碼[ 5ft5 ]

cd /etc/nginx/data/geoip  #如果沒有data,需要手動創建

gunzip GeoIP.dat.gz  #解壓
gunzip GeoLiteCity.dat.gz  #解壓

4.編譯安裝

基本工作準備完成后我們就可以ngx_http_geoip_module編譯進nginx。ngx_http_geoip_module文檔{:target="_blank"}
默認情況下不構建此模塊,應使用--with-http_geoip_module配置參數啟用它。

之前在nginx平滑升級中小菜編譯nginx的源碼包放在/opt/download/nginx-1.14.2文件夾下。

cd /opt/download/nginx-1.14.2

獲取編譯參數

nginx -V

輸出

–prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt=’-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC’ --with-ld-opt=’-Wl,-z,relro -Wl,-z,now -pie’

添加編譯參數--with-http_geoip_module

./configure --prefix=/opt/nginx --sbin-path=/opt/nginx/sbin/ --modules-path=/opt/nginx/lib64/modules --conf-path=/opt/nginx/conf/nginx.conf --error-log-path=/opt/nginx/log/error.log --http-log-path=/opt/nginx/log/access.log --pid-path=/opt/nginx/run/nginx.pid --lock-path=/opt/nginx/run/nginx.lock --http-client-body-temp-path=/opt/nginx/cache/client_temp --http-proxy-temp-path=/opt/nginx/cache/proxy_temp --http-fastcgi-temp-path=/opt/nginx/cache/fastcgi_temp --http-uwsgi-temp-path=/opt/nginx/cache/uwsgi_temp --http-scgi-temp-path=/opt/nginx/cache/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --with-http_geoip_module

編譯

./configure  上面編譯參數 

安裝

make && make install

如果在編譯中有錯誤,查看最上面的編譯時出錯排錯。希望對小伙伴們有用

檢測

nginx -V

查看輸出編譯參數有沒有--with-http_geoip_module,有就證明安裝好了。

nginx geoip2

Nginx Geoip2 處理不同國家 (或城市) 的訪問

前言

最近搞了一套AB站(不是acfun和bilibili,AB站:文中的AB站指的是同一個域名,可返回兩種不同的資源),客戶主要是做谷歌和FaceBook推廣,A站是為了過審和過平臺檢查,B站是目標網站主要推廣日本地區。 日本國家的用戶訪問 http://www.abc.com 看到的是B站,非日本國家的用戶訪問 http://www.abc.com 看到的是A站。

img

當時想了三個方案,最終決定使用Nginx+GeoIP2

  • √ Nginx+GeoIP2
  • 可以拿到請求IP的國家和城市信息
  • 可以讓開發者對于請求的IP進行各種個性化Nginx配置
  • 可以將請求IP的地理位置通過php-fpm傳遞php程序
  • 定時更新MaxMind免費數據庫(GeoLite2-Country.mmdb + GeoLite2-City.mmdb)完成完美閉環
  • maxmind公司2002年成立至今,靠譜
  • × 使用IP識別接口:穩定的需要收費(也不能保證100%高可用:限頻、響應時間、接口異常等因素),免費的無法保證穩定性,接口遠遠沒有將GeoLite數據放在本地穩定
  • × DNS根據地域解析:cloudflare收費略貴,國內cloudxns已關閉免費服務(免費的東西說變就變,論planB的重要性)

TIPS: 網上大部分都是GeoIP老版本的 已經不適用了,GeoIP依賴MaxMind的IP數據,需要頻繁更新(自動化腳本定時更新) 感興趣又不懶的部署的朋友可直接跳到最后有docker體驗

作者環境(2020.05.19)

  • CentOS7.2
  • libmaxminddb 1.3.2
  • Nginx 1.14.2

安裝GeoIP2 依賴

$ wget https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz
$ tar -zxvf libmaxminddb-1.3.2.tar.gz
$ cd libmaxminddb-1.3.2
$ ./configure && make && make install
$ echo /usr/local/lib  >> /etc/ld.so.conf.d/local.conf 
$ ldconfig

下載GeoIP數據

$ git clone https://github.com/ar414-com/nginx-geoip2
$ cd nginx-geoip2
$ tar -zxvf GeoLite2-City_20200519.tar.gz
$ mv ./GeoLite2-City_20200519/GeoLite2-City.mmdb /usr/share/GeoIP/
$ tar -zxvf GeoLite2-Country_20200519.tar.gz
$ mv ./GeoLite2-Country_20200519/GeoLite2-Country.mmdb /usr/share/GeoIP/
$ # /usr/share/GeoIP 目錄不存在的話可自己創建,Tips:不一定要放在這 隨便放在哪
$ # Nginx配置的時候才需要用到數據路徑

將 GeoIP2 模塊編譯到 Nginx 中

下載GeoIP2模塊

$ cd ~
$ git clone https://github.com/ar414-com/nginx-geoip2

編譯到已安裝的Nginx

\1. 查看nginx安裝目錄nginx -V > --prefix=/www/server/nginx

[圖片上傳失敗...(image-bb236f-1631117696536)]

\2. 原封不動帶上之前的編譯參數,再在后面添加Geoip2的模塊參數

--add-module=/root/nginx-geoip2/ngx_http_geoip2_module

$ cd /www/server/nginx
$ ./configure --user=www --group=www \ --prefix=/www/server/nginx \
--with-openssl=/www/server/nginx/src/openssl \
--add-module=/www/server/nginx/src/ngx_devel_kit \
--add-module=/www/server/nginx/src/lua_nginx_module \ --add-module=/www/server/nginx/src/ngx_cache_purge \
--add-module=/www/server/nginx/src/nginx-sticky-module
--add-module=/www/server/nginx/src/nginx-http-concat \
--with-http_stub_status_module --with-http_ssl_module \
--with-http_v2_module --with-http_image_filter_module \
--with-http_gzip_static_module --with-http_gunzip_module \
--with-stream --with-stream_ssl_module --with-ipv6 \
--with-http_sub_module --with-http_flv_module \
--with-http_addition_module --with-http_realip_module \
--with-http_mp4_module --with-ld-opt=-Wl,-E --with-pcre=pcre-8.40 \
--with-ld-opt=-ljemalloc \
--add-module=/root/nginx-geoip2/ngx_http_geoip2_module
$ make
$ rm -f /www/server/nginx/sbin/nginx.old
$ mv /www/server/nginx/sbin/nginx /www/server/nginx/sbin/nginx.old
$ cp ./objs/nginx /www/server/nginx/sbin/nginx
$ make upgrade
$ #檢查是否安裝成功
$ nginx -V

重新安裝Nginx

簡約安裝,方便測試

$ wget https://nginx.org/download/nginx-1.14.2.tar.gz
$ tar zxvf nginx-1.14.2.tar.gz
$ cd nginx-1.14.2
$ ./configure --user=www --group=www \
--prefix=/www/server/nginx  \
--add-module=/root/nginx-geoip2/ngx_http_geoip2_module
$ make && make install

使用 GeoIP2

http{
    ...

    geoip2 /usr/local/share/GeoIP/GeoLite2-Country.mmdb {
          $geoip2_country_code country iso_code;
    }

    map $geoip2_country_code $is_jp_country {
        default no;
        JP yes;
    }

    server {
        listen       80;
        server_name  localhost;
        #加上響應頭方便調試
        add_header country $geoip2_country_code;


        location / {

            set $rootpath html/a;
            if ($is_jp_country = no) {
              set $rootpath html/b;
            }

            add_header rootpath $rootpath;
            add_header country $geoip2_country_code;
            root $rootpath;

            index index.html index.htm;

        }
    }
}

docker 體驗

感興趣又懶得弄的朋友可直接作者上傳的鏡像進行體驗

獲取鏡像

$ docker pull ar414/nginx-geoip2

運行

$ docker run -it -d -p 80:80 -p 443:443 --rm ar414/nginx-geoip2

測試

國內訪問

[圖片上傳失敗...(image-26dad1-1631117696536)]

img

日本訪問

[圖片上傳失敗...(image-6ee5b4-1631117696537)]

img

5.配置模塊

geoip_country

Syntax: geoip_country file;
Default: —
Context: http
參數名 描述
$geoip_country_code 兩個字母的國家/地區代碼,例如“RU”,“US”
$geoip_country_code3 三個字母的國家/地區代碼,例如“RUS”,“USA”
$geoip_country_name 國名,例如“俄羅斯聯邦”,“美國”

geoip_city

Syntax: geoip_city file;
Default: —
Context: http
參數名 描述
$geoip_area_code 電話區號(僅限美國)
$geoip_city_continent_code 兩個字母的大陸代碼,例如“EU”,“NA”
$geoip_city_country_code 兩個字母的國家/地區代碼,例如“RU”,“US”
$geoip_city_country_code3 三個字母的國家/地區代碼,例如“RUS”,“USA”
$geoip_city_country_name 國名,例如“俄羅斯聯邦”,“美國”
$geoip_dma_code 根據Google AdWords API中的地理位置定位,美國的DMA區域代碼(也稱為“都市代碼”)
$geoip_latitude 緯度
$geoip_longitude 經度
$geoip_region 雙符號國家區域代碼(地區,領土,州,省,聯邦土地等),例如“48”,“DC”
$geoip_region_name 國家地區名稱(地區,領土,州,省,聯邦土地等),例如“莫斯科市”,“哥倫比亞特區”
$geoip_city 城市名稱,例如“莫斯科”,“華盛頓”
$geoip_postal_code 郵政編碼

geoip_org

Syntax: geoip_org file;
Default: —
Context: http
參數名 描述
$geoip_org 組織名稱,例如“墨爾本大學”

geoip_proxy

Syntax: geoip_proxy address | CIDR;
Default: —
Context: http

定義可信地址。當請求來自可信地址時,將使用來自X-Forwarded-For請求頭字段的地址。

geoip_proxy_recursive

Syntax: geoip_proxy_recursive on | off;
Default: geoip_proxy_recursive off;
Context: http

如果禁用遞歸搜索,則不使用與其中一個可信地址匹配的原始客戶端地址,而是使用X-Forwarded-For中發送的最后一個地址。如果啟用遞歸搜索,則不使用與其中一個可信地址匹配的原始客戶端地址,而是使用在X-Forwarded-For中發送的最后一個不可信地址。

6.配置教程

服務目錄

/etc/nginx/conf.d
|-geoip.conf

geoip.conf

geoip_country /etc/nginx/data/geoip/GeoIP.dat;
geoip_city /etc/nginx/data/geoip/GeoLiteCity.dat;
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    access_log  /var/log/nginx/log/geoip.access.log  main;

    location / {
        if ($geoip_country_code != CN) {
            return 403;
        }
        root   /opt/app/code;
        index  index.html index.htm;
    }

   location /myip {
        default_type text/plain;
        return 200 "$remote_addr $geoip_country_name $geoip_country_code $geoip_city";
   }

}

日志示例

#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"';
    
    log_format json_analytics escape=json '{'
        '"msec": "$msec", ' # request unixtime in seconds with a milliseconds resolution
        '"connection": "$connection", ' # connection serial number
        '"connection_requests": "$connection_requests", ' # number of requests made in connection
        '"pid": "$pid", ' # process pid
        '"request_id": "$request_id", ' # the unique request id
        '"request_length": "$request_length", ' # request length (including headers and body)
        '"remote_addr": "$remote_addr", ' # client IP
        '"remote_user": "$remote_user", ' # client HTTP username
        '"remote_port": "$remote_port", ' # client port
        '"time_local": "$time_local", '
        '"time_iso8601": "$time_iso8601", ' # local time in the ISO 8601 standard format
        '"request": "$request", ' # full path no arguments if the request
        '"request_uri": "$request_uri", ' # full path and arguments if the request
        '"args": "$args", ' # args
        '"status": "$status", ' # response status code
        '"body_bytes_sent": "$body_bytes_sent", ' # the number of body bytes exclude headers sent to a client
        '"bytes_sent": "$bytes_sent", ' # the number of bytes sent to a client
        '"http_referer": "$http_referer", ' # HTTP referer
        '"http_user_agent": "$http_user_agent", ' # user agent
        '"http_x_forwarded_for": "$http_x_forwarded_for", ' # http_x_forwarded_for
        '"http_host": "$http_host", ' # the request Host: header
        '"server_name": "$server_name", ' # the name of the vhost serving the request
        '"request_time": "$request_time", ' # request processing time in seconds with msec resolution
        '"upstream": "$upstream_addr", ' # upstream backend server for proxied requests
        '"upstream_connect_time": "$upstream_connect_time", ' # upstream handshake time incl. TLS
        '"upstream_header_time": "$upstream_header_time", ' # time spent receiving upstream headers
        '"upstream_response_time": "$upstream_response_time", ' # time spend receiving upstream body
        '"upstream_response_length": "$upstream_response_length", ' # upstream response length
        '"upstream_cache_status": "$upstream_cache_status", ' # cache HIT/MISS where applicable
        '"ssl_protocol": "$ssl_protocol", ' # TLS protocol
        '"ssl_cipher": "$ssl_cipher", ' # TLS cipher
        '"scheme": "$scheme", ' # http or https
        '"request_method": "$request_method", ' # request method
        '"server_protocol": "$server_protocol", ' # request protocol, like HTTP/1.1 or HTTP/2.0
        '"pipe": "$pipe", ' # "p" if request was pipelined, "." otherwise
        '"gzip_ratio": "$gzip_ratio", '
        '"http_cf_ray": "$http_cf_ray",'
        '"geoip_country_code": "$geoip_country_code"'
    '}';

    access_log log/json_access.log json_analytics;
    
    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;
    geoip_country data/geoip/GeoIP.dat;
    #geoip_city data/geoip/GeoLiteCity.dat;
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;
        #access_log  /var/log/nginx/log/geoip.access.log  main;

        location / {
            if ($geoip_country_code != EN) {
                return 403;
            }
            root   /opt/app/code;
            index  index.html index.htm;
        }   

        location /myip {
            default_type text/plain;
            return 200 "$remote_addr $geoip_country_name $geoip_country_code $geoip_city";
        }

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        

        #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;
    #    }
    #}
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容