nginx

目录

目录

简介

 nginx的特性与优点

nginx的优点

nginx的功能及应用类别

nginx的基本功能

nginx的扩展功能

nginx的应用类别

nginx的模块与工作原理

nginx的工作原理

nginx的安装与配置 

nginx的配置文件详解 

nginx.conf配置详解

用于调试、定位问题的配置参数

daemon

进程

配置文件备份

正常运行必备的配置参数

优化性能的配置参数

事件相关的配置:event{}段中的配置参数

 网络连接相关的配置参数

fastcgi的相关配置参数

nginx作为web服务器时使用的配置:http{}段的配置参数

访问控制

 https配置

 ​平滑升级: 



简介

nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。

nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。

第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

nginx的特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

 nginx的特性与优点

nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:

  • 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
  • 使用epoll and kqueue作为开发模型
  • nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
  • nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

nginx的优点

  • 高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
  • 内存消耗少:在3万并发连接下,开启的10个nginx进程才消耗150M内存(15M*10=150M)
  • 配置文件非常简单:风格跟程序一样通俗易懂
  • 成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
  • 支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
  • 内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
  • 节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
  • 稳定性高:用于反向代理,宕机的概率微乎其微
  • 模块化设计:模块可以动态编译
  • 外围支持好:文档全,二次开发和模块较多
  • 支持热部署:可以不停机重载配置文件
  • 支持事件驱动、AIO(AsyncIO,异步IO)、mmap(Memory Map,内存映射)等性能优化

nginx的功能及应用类别

nginx的基本功能

  • 静态资源的web服务器,能缓存打开的文件描述符
  • http、smtp、pop3协议的反向代理服务器
  • 缓存加速、负载均衡
  • 支持FastCGI(fpm,LNMP),uWSGI(Python)等
  • 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  • 支持SSL

nginx的扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制
  • 支持速率限制,支持并发数限制

nginx的应用类别

  • 使用nginx结合FastCGI运行PHP、JSP、Perl等程序
  • 使用nginx作反向代理、负载均衡、规则过滤
  • 使用nginx运行静态HTML网页、图片
  • nginx与其他新技术的结合应用

nginx的模块与工作原理

nginx的模块从结构上分为核心模块、基础模块和第三方模块

  • HTTP模块、EVENT模块和MAIL模块等属于核心模块
  • HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
  • HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块

用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大

nginx模块从功能上分为三类,分别是:

  • Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。handlers处理器模块一般只能有一个
  • Filters(过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由nginx输出
  • Proxies(代理器模块)。就是nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如fastcgi等操作交互,实现服务代理和负载均衡等功能

nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

  • nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
    • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部
    • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
    • 配置模块:提供包含机制

具体的指令,请参考nginx官方文档

nginx的工作原理

nginx的模块直接被编译进nginx,因此属于静态编译方式。

启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。

在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request

下图展示了nginx模块一次常规的HTTP请求和响应的过程

下图展示了基本的WEB服务请求步骤

nginx的安装与配置 

//创建nginx系统用户
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx

//下载包组
[root@localhost ~]# yum -y groups mark install 'Development Tools'
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * epel: mirrors.bfsu.edu.cn
Marked install: Development Tools

//安装依赖包
[root@localhost ~]# yum install -y gcc gcc-c++ pcre-devel gd-devel openssl openssl-devel 

//创建nginx存放日志的目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx

//从网上拉去压缩包
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget http://nginx.org/download/nginx-1.2.0.tar.gz
--2021-10-25 14:21:05--  http://nginx.org/download/nginx-1.2.0.tar.gz
正在解析主机 nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5704::6, ...
正在连接 nginx.org (nginx.org)|52.58.199.22|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:716067 (699K) [application/octet-stream]
正在保存至: “nginx-1.2.0.tar.gz”

100%[=================>] 716,067      174KB/s 用时 4.0s   

2021-10-25 14:21:11 (174 KB/s) - 已保存 “nginx-1.2.0.tar.gz” [716067/716067])

[root@localhost src]# ls
debug  kernels  nginx-1.2.0.tar.gz
[root@localhost src]# 

//解压至/usr/local
[root@localhost src]# tar xf nginx-1.2.0.tar.gz -C /usr/local/
[root@localhost src]# cd /usr/local/
[root@localhost local]# ls
bin  games    lib    libexec      sbin   src
etc  include  lib64  nginx-1.2.0  share
[root@localhost local]# mv nginx-1.2.0/ nginx

//编译安装
[root@localhost nginx]# ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-debug \
> --with-http_ssl_module \
> --with-http_realip_module \
> --with-http_image_filter_module \
> --with-http_gzip_static_module \
> --with-http_stub_status_module \
> --http-log-path=/var/log/nginx/access.log \
> --error-log-path=/var/log/nginx/error.log
checking for OS
 + Linux 3.10.0-862.el7.x86_64 x86_64
checking for C compiler ... found
checking for gcc builtin atomic operations ... found
checking for C99 variadic macros ... found

......

Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + md5: using OpenSSL library
  + sha1: using OpenSSL library
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/var/log/nginx/error.log"
  nginx http access log file: "/var/log/nginx/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

[root@localhost nginx]# make && make install

//配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# . /etc/profile.d/nginx.sh

//测试
[root@localhost ~]# nginx 
[root@localhost ~]# ss -antl
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128     *:80                  *:*                  
LISTEN      0      128     *:22                  *:*                  
LISTEN      0      100    127.0.0.1:25                  *:*                  
LISTEN      0      128    :::22                 :::*                  
LISTEN      0      100       ::1:25                 :::*                  
[root@localhost ~]# 



nginx的配置文件详解 

主配置文件:/usr/local/nginx/conf/nginx.conf

  • 默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
  • 可以在启动nginx时通过-c选项来指定要读取的配置文件

nginx常见的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME类型关联的扩展文件
fastcgi.conf与fastcgi相关的配置
proxy.conf与proxy相关的配置
sites.conf配置nginx提供的网站,包括虚拟主机

nginx.conf配置详解

nginx.conf的内容分为以下几段:

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定义event模型工作特性
  • http {}:定义http协议相关的配置

配置指令:要以分号结尾,语法格式如下:

derective value1 [value2 ...];

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value

用于调试、定位问题的配置参数

daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志

daemon

//修改配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
#user  nobody;
worker_processes  1;
daemon off;                       //添加此行,不添加则daemon默认为off关闭

//重启nginx测试是否在前台运行
[root@localhost ~]# nginx  -s  stop ; nginx 


^C[root@localhost ~]# ss -antl        //ctrl c退出后,nginx服务也停止
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128     *:22                  *:*                  
LISTEN      0      100    127.0.0.1:25                  *:*                  
LISTEN      0      128    :::22                 :::*                  
LISTEN      0      100       ::1:25                 :::*                  
[root@localhost ~]# 

错误日志

//查看日志目录
[root@localhost ~]# ll /usr/local/nginx/logs/
总用量 4
-rw-r--r-- 1 root root 5 10月 25 14:51 nginx.pid

//开启错误日志功能
[root@localhost ~]# cat /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  3;
daemon on;

error_log  logs/error.log;        //取消这行注释
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

//重新加载配置文件,查看
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ll /usr/local/nginx/logs/
总用量 4
-rw-r--r-- 1 root root 0 10月 25 15:07 error.log
-rw-r--r-- 1 root root 5 10月 25 14:51 nginx.pid
[root@localhost ~]# cat /usr/local/nginx/logs/error.log 
[root@localhost ~]# 

手动触发错误

查看错误日志

[root@localhost ~]# cat /usr/local/nginx/logs/error.log 
2021/10/25 15:08:45 [error] 26673#0: *1 open() "/usr/local/nginx/html/123123" failed (2: No such file or directory), client: 192.168.75.1, server: localhost, request: "GET /123123 HTTP/1.1", host: "192.168.75.144"
[root@localhost ~]# 

进程

//查看默认进程数
[root@localhost ~]# cat /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  1;        //默认为1
daemon on;

[root@localhost ~]# ps -ef | grep nginx
root       9238      1  0 14:51 ?        00:00:00 nginx: master process nginx
nginx      9239   9238  0 14:51 ?        00:00:00 nginx: worker process //只有一个worker进程
root      14469   1461  0 14:56 pts/0    00:00:00 grep --color=auto nginx

//修改进程数为3
[root@localhost ~]# cat /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  3;
daemon on;

//重新加载配置文件
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ps -ef | grep nginx
root       9238      1  0 14:51 ?        00:00:00 nginx: master process nginx
nginx     19039   9238  0 15:00 ?        00:00:00 nginx: worker process
nginx     19040   9238  0 15:00 ?        00:00:00 nginx: worker process
nginx     19041   9238  0 15:00 ?        00:00:00 nginx: worker process
root      19191   1461  0 15:00 pts/0    00:00:00 grep --color=auto nginx

配置文件备份

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# cp /usr/local/nginx/conf/nginx.conf /opt/
[root@localhost ~]# cp /usr/local/nginx/conf/mime.types /opt/
[root@localhost ~]# ls /opt/
mime.types  nginx.conf

//指定配置文件启动nginx
[root@localhost ~]# nginx -c /opt/nginx.conf 
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
[root@localhost ~]# 

正常运行必备的配置参数

user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size;    //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

设置默认运行nginx用户为nginx

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# cat /usr/local/nginx/conf/nginx.conf

user nginx ;         //取消注释,更改为nginx
worker_processes  1;

//进程查看
[root@localhost ~]# ps -ef | grep nginx
root        1933       1  0 21:55 ?        00:00:00 nginx: master process nginx
nginx       1934    1933  0 21:55 ?        00:00:00 nginx: worker process
root       14528    2463  0 22:02 pts/0    00:00:00 grep --color=auto nginx

指定nginx守护进程的pid文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
8 
9 pid        logs/nginx.pid;         //取消注释,默认为此

//重新读取配置文件生效
[root@localhost ~]# nginx -s reload

设置所有worker进程最大可以打开的文件数,默认为1024

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
  2 user nginx ;
  3 worker_processes  1;
  4 worker_rlimit_nofile 10240;  //添加此行,设置所有worker进程最大可以打开的文件数,默认为1024,最大为65535


//用法
Syntax:	worker_rlimit_nofile number;
Default:	1024
Context:	main

指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

worker_rlimit_core size; 

优化性能的配置参数

worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值

worker_cpu_affinity cpumask …; 将进程绑定到某cpu中,避免频繁刷新缓存,似于专人专事,建议不要把所有的cpu都绑定,至少留一个cpu来让系统正常运行

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
  2 user nginx ;
  3 worker_processes  1;
  4 worker_rlimit_nofile 10240;
  5 worker_cpu_affinity 0001 0010 0100;  //添加此行,为前面增加的三个worker绑定核心

//查看
[root@localhost ~]# nginx -s reload
[root@localhost ~]# 

//查看进程是否生效:
top 大写L搜索nginx 小写t 选中p quit退出即可

计时器解析度。降低此值,可减少gettimeofday()系统调用的次数。减少worker线程中的定时器分辨率,从而减少系统呼叫的数量。默认情况下,每次收到内核事件时都会被调用。随着分辨率的降低,每个指定呼叫一次

//用法
Syntax:	timer_resolution interval;
Default: —
Context: main

//例
timer_resolution 60ms;

指明worker进程的nice值,优先级是-20到19,指定的数字越小,优先级越高,相对优先级(可以调整) ,绝对优先级,100到139(无法调整) ,提高优先级可以先进行处理

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
  2 user nginx ;
  3 worker_processes  3;
  4 worker_rlimit_nofile 10240;
  5 worker_cpu_affinity 0001 0010 0100;
  6 worker_priority -20  //-20为最优先

//查看
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ps -ef | grep nginx
root       35058       1  0 22:15 ?        00:00:00 nginx: master process nginx
nginx      45840   35058  0 22:21 ?        00:00:00 nginx: worker process
nginx      45841   35058  0 22:21 ?        00:00:00 nginx: worker process
nginx      45842   35058  0 22:21 ?        00:00:00 nginx: worker process
root       46076    2463  0 22:22 pts/0    00:00:00 grep --color=auto nginx
[root@localhost ~]# 

事件相关的配置:event{}段中的配置参数

accept_mutex {off|on}; master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求

//用法
Syntax:    accept_mutex on | off;
Default: accept_mutex off;
Context: events

lock_file file; accept_mutex用到的互斥锁锁文件路径

//用法
Syntax:	lock_file file;
Default: lock_file logs/nginx.lock;
Context: main

worker_connections #; 每个进程能够接受的最大连接数

//用法
Syntax:	worker_connections number;
Default: worker_connections 512;
Context: events

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 15 events {
 16     worker_connections  20480;  //默认为1024
 17 }


//测试,用30000并发访问本机ip
[root@localhost ~]# ab -n 30000 http://192.168.75.142/index.html
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.75.142 (be patient)
Completed 3000 requests
Completed 6000 requests
Completed 9000 requests
Completed 12000 requests
Completed 15000 requests
Completed 18000 requests
Completed 21000 requests
Completed 24000 requests
Completed 27000 requests
Completed 30000 requests
Finished 30000 requests


Server Software:        nginx/1.20.1
Server Hostname:        192.168.75.142
Server Port:            80

Document Path:          /index.html
Document Length:        612 bytes

Concurrency Level:      1
Time taken for tests:   3.656 seconds
Complete requests:      30000
Failed requests:        0
Total transferred:      25350000 bytes
HTML transferred:       18360000 bytes
Requests per second:    8206.21 [#/sec] (mean)
Time per request:       0.122 [ms] (mean)
Time per request:       0.122 [ms] (mean, across all concurrent requests)
Transfer rate:          6771.73 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       1
Processing:     0    0   0.0      0       3
Waiting:        0    0   0.0      0       2
Total:          0    0   0.0      0       3

Percentage of the requests served within a certain time (ms)
  50%      0
  66%      0
  75%      0
  80%      0
  90%      0
  95%      0
  98%      0
  99%      0
 100%      3 (longest request)
[root@localhost ~]# 

 网络连接相关的配置参数

keepalive_timeout number;    //长连接的超时时长,默认为65s
keepalive_requests number;    //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;    //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;    //读取http请求报文首部的超时时长
client_body_timeout number;    //读取http请求报文body部分的超时时长
send_timeout number;    //发送响应报文的超时时长

长连接的超时时长,默认为65s

//用法
Syntax:	keepalive_timeout timeout [header_timeout];
Default: keepalive_timeout 65s;
Context: http, server, location


[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 33     #keepalive_timeout  0;
 34     keepalive_timeout  65; //默认为65
 35 

keepalive_requests number; 在一个长连接上所能够允许请求的最大资源数

keepalive_requests number;   # 可以添加在http段,server段,location段


[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 38     server {
 39         listen       80;
 40         server_name  localhost;
 41         keepalived_requests 10000   # 可以添加在server段
 42 
 43         #charset koi8-r;

为指定类型的UserAgent(用户代理)禁用长连接

//用法
Syntax:	keepalive_requests number;
Default: keepalive_requests 1000;
Context: http, server, location

fastcgi的相关配置参数

LNMP:php要启用fpm模型
配置示例如下:

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

nginx作为web服务器时使用的配置:http{}段的配置参数

http {//协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
  upstream {//负载均衡配置
    ...
  }
  server {//服务器级别,每个server类似于httpd中的一个<VirtualHost>
    listen 80;
    server_name localhost;
    location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}

http{}段配置指令:
server {}:定义一个虚拟主机,示例如下:

server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

listen:指定监听的地址和端口

listen address[:port];
listen port;

访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
示例:

allow 192.168.1.1/32;
allow 172.16.0.0/16;
deny all;

实例:

禁止本机访问

//修改配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            deny 192.168.75.142;
            root   html;
            index  index.html index.htm;
        }

//测试
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
[root@localhost ~]# curl 192.168.75.142
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# 

禁止除本机以外的主机访问

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
     location / {
            allow 192.168.75.142;
            deny all;
            root   html;
            index  index.html index.htm;
        } 

//测试
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload

//本机访问
[root@localhost ~]# curl 192.168.75.142
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@localhost ~]# 

//测试,除本机外主机访问

基于用户

auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"

user_auth_file内容格式为:

username:password

这里的密码为加密后的密码串,建议用htpasswd来创建此文件:

基于用户

//设置用户和密码
[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass yang
New password: 
Re-type new password: 
Adding password for user yang
[root@localhost ~]# cat /usr/local/nginx/conf/.pass
yang:$apr1$2eebM6li$yOJijD825YKtA8B5tO1K/0

//修改配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location /test {
            auth_basic "test";
            auth_basic_user_file ".pass";
            root    html;
            index    index.html;
        }

//测试
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload


//创建test目录和文件
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
404.html  index.html  RNG
50x.html  index.php
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost html]# mkdir test
[root@localhost html]# cp 404.html test/index.html
[root@localhost html]# nginx -s reload

 https配置

//创建储存密钥目录
[root@localhost ~]# mkdir -p /etc/pki/CA
[root@localhost ~]# cd /etc/pki/CA
[root@localhost CA]# mkdir private
[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:yang
Organizational Unit Name (eg, section) []:yang
Common Name (eg, your name or your server's hostname) []:test.yang.com
Email Address []:1@2.com
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial
[root@localhost CA]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
........................+++++
..........................................................................................................................................................+++++
e is 65537 (0x010001)
[root@localhost CA]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:yang
Organizational Unit Name (eg, section) []:yang
Common Name (eg, your name or your server's hostname) []:test.yang.com
Email Address []:1@2.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost CA]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 27 13:46:32 2021 GMT
            Not After : Oct 27 13:46:32 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = yang
            organizationalUnitName    = yang
            commonName                = test.yang.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                50:E3:FC:13:35:94:11:7F:33:DC:3D:CD:96:56:E5:1A:5C:A5:B2:C7
            X509v3 Authority Key Identifier: 
                keyid:45:AD:90:3E:D7:8C:23:A4:91:F0:84:F1:17:35:D1:34:45:D6:92:C6

Certificate is to be certified until Oct 27 13:46:32 2022 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost CA]# cp nginx.key /usr/local/nginx/conf/ssl/
[root@localhost CA]# cp nginx.crt /usr/local/nginx/conf/ssl/
[root@localhost CA]#  ls private/
cakey.pem
[root@localhost CA]# 
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
//修改配置文件

    server {        //取消注释并修改内容
        listen       443 ssl;
        server_name  test.yang.com;

        ssl_certificate      ssl/nginx.crt;
        ssl_certificate_key  ssl/nginx.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;
        }
    }

}

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
[root@localhost ~]# 


测试:

 开启状态界面

开启status:

location /status {
  stub_status {on | off};
  allow 172.16.0.0/16;
  deny all;
}

访问状态页面的方式:http://server_ip/status

状态页面信息详解:

状态码表示的意义
Active connections 2当前所有处于打开状态的连接数
accepts总共处理了多少个连接
handled成功创建多少握手
requests总共处理了多少个请求
Readingnginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writingnginx返回给客户端的Header信息数,表示请求已经接收完成,
且正处于处理请求或发送响应的过程中的连接数
Waiting开启keep-alive的情况下,这个值等于active - (reading + writing),
意思就是Nginx已处理完正在等候下一次请求指令的驻留连接
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location /status {
            stub_status;
        }
    
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload


[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
        location /status {
            stub_status;
            allow 192.168.75.142;
            deny all:
        }
root@localhost ~]# nginx -s reload
[root@localhost ~]# curl 192.168.75.142/status
Active connections: 1 
server accepts handled requests
 5 5 4 
Reading: 0 Writing: 1 Waiting: 0

rewrite

语法:rewrite regex replacement flag;,如:

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

此处的$1用于引用(.*.jpg)匹配到的内容,又如:

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

如上例所示,replacement可以是某个路径,也可以是某个URL

 

常见的flag

flag作用
last基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个
一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理
而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break中止Rewrite,不再继续匹配
一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,
且不再会被当前location内的任何rewrite规则所检查
redirect以临时重定向的HTTP状态302返回新的URL
permanent以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
[]匹配指定字符集内的任意字符
[^]匹配任何不包括在指定字符集内的任意字符串
|匹配 | 之前或之后的实体
()分组,组成一组用于匹配的实体,通常会有 | 来协助

捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$       //字符串为“hi sir”捕获的结果:$1=hi$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了
//放入图片以供读取
[root@localhost imgs]# ls
1.jpg  2.png

//编辑配置文件
[root@localhost imgs]# vim /usr/local/nginx/conf/nginx.conf
        location /images {
            rewrite ^/images/(.*\.png)$ /imgs/$2 break;
        }

[root@localhost imgs]# nginx -s reload

 

 

又如:

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

如上例所示,replacement可以是某个路径,也可以是某个URL

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf

   location /images {
            rewrite ^/images/(.*\.jpg)$ https://cn.bing.com/images/search?view=detailV2&ccid=cBD%2fyflL&id=F6CB283786932DBD38FC61BEB0B0CB042D8F7450&thid=OIP.cBD_yflLj4r4YOsD8QIKgAHaEo&mediaurl=https%3a%2f%2fupfile2.asqql.com%2fupfile%2fhdimg%2fwmtp%2fwmtp%2f2018-07%2f08%2f18_7_8_17_15_18t60ksq4a.jpg&exph=625&expw=1000&q=%e5%9b%be%e7%89%87&simid=608010766181880770&FORM=IRPRST&ck=2E69412BB6DFF127AF693403AEF07FA8&selectedIndex=136 break;
        }

[root@localhost html]# nginx -s reload
[root@localhost html]# 

if

语法:if (condition) {...}

应用场景:

  • server段
  • location段

常见的condition

  • 变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
  • 以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
  • 正则表达式的模式匹配操作
    • ~:区分大小写的模式匹配检查
    • ~*:不区分大小写的模式匹配检查
    • !~和!~*:对上面两种测试取反
  • 测试指定路径为文件的可能性(-f,!-f)
  • 测试指定路径为目录的可能性(-d,!-d)
  • 测试文件的存在性(-e,!-e)
  • 检查文件是否有执行权限(-x,!-x)

6.15.1 基于浏览器实现分离案例

if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

6.15.2 防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值