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 依赖

  • 官方GitHub
  • 官方下载地址
$ 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数据

  • 官方下载地址
  • github下载地址
$ 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;
    #    }
    #}
}

你可能感兴趣的:(linxu nginx非常详细--yum安装 编译安装 模块安装 日志格式)