Nginx 介绍与使用

Nginx 简介

Nginx 概述

Nginx 是一款由俄罗斯开放的开源的高性能的 HTTP服务器和反向代理 web 服务器,同时还支持 IMAP/POP3/SMTP 服务。其特点是高性能、稳定、消耗硬件资源小、能够处理大并发

Nginx 功能

  • web 服务

  • 负载均衡 (反向代理)

  • web cache (web 缓存)

Nginx 优点

  • 支持高并发,能支持几万并发连接(特别是静态小文件业务环境)

  • 内存消耗小,在3万并发连接下,开启10个Nginx线程消耗的内存不到200MB。

  • 配置简单,使用灵活,支持Rewrite重写规则。

  • 能种类比较多,web,cache,proxy。

  • 支持异步网络I/O事件模型epoll。

Nginx 模块划分

结构划分

  • 核心模块:HTTP、EVENT模块和MAIL模块
  • 基础模块:HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块
  • 第三方模块:HTTP Upstream Request Hash模块、Notice模块和HTTP Access Key模块。

功能划分

Handlers(处理器模块):此类模块直接出来请求,并输出内容和修改headers信息等操作。Handlers处理器模块一般只能有一个。

Filters(过滤器模块):此类模块主要对其他处理器模块输出的内容进行修改操作,最后有nginx输出。

Proxies(代理类模块):此类模块是nginx的HTTP Upstream质量的模块,这些模块主要与后端一些服务(例如FastCGI)进行交互,实现服务代理和负载均衡等功能。

Nginx 进程模型

Nginx在启动后,会有一个master进程和多个worker进程。

Master 进程

1.接收外界传递给Nginx的信号,进而管理服务的状态等;

2.管理worker进程,向各worker进程发送信号,监控worker进程的运行状态,当worker进程异常情况下退出后,会自动重新启动新的worker进程;

3.master进程充当整个进程组与用户的交互接口,同时对进程进行监护。它不需要处理网络事件,不负责业务的执行,只会通过管理worker进程来实现重启服务、平滑升级、更换日志文件、配置文件实时生效等功能。

Worker 进程

1.处理基本的网络事件,多个worker进程之间是对等且独立,他们同等竞争来自客户端的请求。

2.一个请求,只可能在一个worker进程中处理,一个worker进程,不可能处理其它进程的请求。

2.worker进程的个数是可以设置的,一般我们会设置与机器cpu核心数一致;

Nginx 安装

实验环境

系统类型 IP地址 主机名 硬件
CentOS 7.6 1810 10.4.7.7 www.onelpc.com 内存:2G

安装 Nginx 所需依赖

yum install -y pcre pcre-devel		
yum install -y openssl openssl-devel

创建 nginx 用户

useradd  -s /sbin/nologin -M nginx 

下载软件包并解压

# 创建目录存放软件包
mkdir -p /server/tools
cd /server/tools

# 下载nginx 软件包
wget http://nginx.org/download/nginx-1.16.1.tar.gz

# 解压
tar xf nginx-1.16.1.tar.gz 
cd nginx-1.16.1/

编译与安装

./configure \
--user=nginx \
--group=nginx \
--prefix=/usr/local/nginx-1.16.1 \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-pcre

make&&make install

创建软连接

ln -s /usr/local/nginx-1.16.1 /usr/local/nginx
ln -s /usr/local/nginx/sbin/  /usr/local/sbin

配置 systemctl 管理

cat >/usr/lib/systemd/system/nginx.service<<EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s QUIT \$MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

启动nginx

systemctl daemon-reload
systemctl start nginx
systemctl enable nginx

访问测试

image-20200301174911355

nginx 常用编译参数说明

-prefix=/usr/local/nginx 				##指定安装位置
--user=nginx --group=nginx 				##指定运行服务的用户和组
--with-http_stub_status_module			##开启状态监听模块 
--conf-path= 							##指向配置文件存放位置
--error-log-path= 						##指向错误日志存放位置
--pid-path= 							##指向pid文件存放位置 
--with-rtsig_module 					##启用rtsig模块支持(实时信号)
--with-select_module 					##启用select模块支持(一种轮询模式,不推荐在高载环境下使用)禁用:--without-select_module
--with-http_ssl_module 					##启用ngx_http_ssl_module支持(使支持https请求,需已安装openssl)
--with-http_xslt_module  				##启用ngx_http_xslt_module支持(过滤转换XML请求)
--with-http_image_filter_module 		##启用ngx_http_image_filter_module支持(传输JPEG/GIF/PNG 图片的一个过滤器)(默认为不启用,要用到gd库) 
--with-http_gzip_static_module 			##启用ngx_http_gzip_static_module支持(在线实时压缩输出数据流)
--with-http_degradation_module  		##启用ngx_http_degradation_module支持(允许在内存不足的情况下返回204或444码)
--without-http_access_module 			##禁用ngx_http_access_module支持(该模块提供了一个简单的基于主机的访问控制,允许或拒绝基于ip地址)
--without-http_auth_basic_module		##禁用ngx_http_auth_basic_module(该模块是可以使用用户名和密码基于http基本认证方法,来保护你的站点或其部分内容)
---without-http_rewrite_module 			##禁用ngx_http_rewrite_module支持(该模块允许使用正则表达式改变URL)
--without-http_fastcgi_module 			##禁用ngx_http_fastcgi_module支持(该模块允许Nginx 与FastCGI 进程交互,并通过传递参数来控制FastCGI 进程工作。)

Nginx 配置文件

nginx 配置文件整体结构

img

1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。

5、location块:配置请求的路由,以及各种页面的处理情况。

Nginx 配置文件内容说明

user  nobody  nobody;			##运行的用户和组
worker_processes  3;			##process数
error_log  logs/error.log;		##错误日志存放位置与日志级别
pid  logs/nginx.pid;			##PID文件路径

events {
	use epoll;				   ##事件驱动模型
    worker_connections  1024;  ##最大连接数的配置
}


http {
    ##设定mime类型,类型由mime.type文件定义
    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"';
    
    access_log  logs/access.log  main;		##服务日志路径与名称
    sendfile  on;				##开启高效传输模式	
    keepalive_timeout  65;  	##长连接超时时间  
    
   	gzip on;					##开启gzip压缩
	gzip_min_length  1k;		##指定最小压缩文件的大小
	gzip_buffers    4  16k;		##指定压缩缓冲区的个数和大小
	gzip_http_version 1.0;		##指定压缩版本
	gzip_comp_level 2;			##指定压缩等级1-9,9等级最高
    ##指定压缩文件类型
	gzip_types  text/plain application/x-javascript text/css application/xml;		

    #配置虚拟主机
    server {
        #虚拟主机使用的端口
        listen       80;
        #虚拟主机域名
        server_name  localhost;

        #虚拟主机支持的字符集
        #charset koi8-r;

        #虚拟主机的访问日志路径
        #access_log  logs/host.access.log  main;

        #定义web根路径
        location / {
            #根目录路径
            root   html;
            #索引页
            index  index.html index.htm;
        }

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

        #定义PHP为本机服务的模型  
        # 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;
        #}

    #https的配置方案
    # 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;
    #    }
    #}
}

注意:修改完配置文件后一定要记得nginx -t检查配置文件是否正确,否则直接重启会导致nginx无法启动。

Nginx 配置实例

Nginx 日志配置

access_log 指令

access_log 用来定义日志级别,日志位置。

日志级别: debug > info > notice > warn > error > crit > alert > emerg

#语法
access_log path format gzi=[level] [buffer=size] [flush=time]
		  # gzip压缩等级
      # buffer设置内存缓冲区大小
      # flush保存在缓冲区中的最长时间
      # 不记录日志:access_log off 
# 例子
access_log   logs/host.access.log  main;

log_format 指令

用来定义记录日志的格式

#日志格式
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

日志格式允许包含的变量:
  $remote_addr, $http_x_forwarded_for 记录客户端IP地址
  $remote_user         	 记录客户端名称
  $request              记录请求的URL和HTTP协议
  $status          	   记录请求状态
  $body_bytes_sent         发送给客户端的字节数,不包括响应头的大小
  $bytes_sent       	 发送给客户端的总字节数
  $connection        	 链接的序列号
  $connection_requests 		 当前通过一个链接获得的请求数量
  $msec       			 日志写入时间,单位为秒,精确是毫秒
  $pipe       	      	  如果请求时通过http流水线发送,pipe值为p,否则为.
  $http_referer              记录从那个页面链接访问过来的
  $http_user_agent        	 记录客户端浏览器相关信息
  $request_length         	 请求的长度
  $request_time           	 请求处理时间,单位为秒,精确度毫秒
  $time_iso8601           	 标准格式下的本地时间
  $time_local                通用日志格式下的本地时间

#@指定为json格式
log_format main_json '{"@timestamp":"$time_local",'
                     '"client_ip": "$remote_addr",'
                     '"request": "$request",'
                     '"status": "$status",'
                     '"bytes": "$body_bytes_sent",'
                     '"x_forwarded": "$http_x_forwarded_for",'
                     '"referer": "$http_referer"'
'}';

Nginx location匹配规则

location指令作用: 用于匹配uri信息,针对不同的uri信息做出不同的处理

# 语法格式
location指令作用: 用于匹配uri信息,针对不同的uri信息做出不同的处理
location匹配方法:
Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }
        location @name { ... }
Default:	—
Context:	server, location

# 匹配优先级
	=       精确匹配                        优先级01
	^~      优先匹配(不识别匹配中的正则信息)    优先级02
	~       模糊匹配(对匹配信息大小写敏感)      优先级03
	~*      模糊匹配(对匹配信息大小写不敏感)    优先级03
	uri     模糊匹配(指定清楚匹配内容)         优先级03
	loaction /  默认匹配的location           优先级最低    

Nginx 访问控制

网站阻止访问模块: Module ngx_http_access_module

## 语法格式
Syntax:	allow address | CIDR | unix: | all;
Default:	—
Context:	http, server, location, limit_except


## 举例说明
[root@web01 nginx]# cat www.conf 
server {
    listen   80;
    server_name  www.bossx.club;
    root  /html/www;
    
    location / {
        index index.html;
        deny  10.4.7.0/24;	#拒绝10.4.7.0 访问
		allow 10.4.7.1;		#允许10.4.7.1 访问
}

网站认证访问模块: ngx_http_auth_basic_module

## 语法格式
Syntax:	auth_basic string | off;             --- 是否开启认证功能
Default:	auth_basic off;
Context:	http, server, location, limit_except
Syntax:	auth_basic_user_file file;           --- 定义密码文件信息

## 举例说明
[root@web01 nginx]# cat www.conf 
server{
    listen 80;
    server_name  www.bossx.club;
    root /var/html/www;
    
    location / {
        index index.html;
        auth_basic bossx_auth;						# 开启认证模块		
        auth_basic_user_file conf.d/http.password;	# 指定的密码文件路径
        ##可以使用htpasswd命令生成密码(在httpd-tools软件包中),`htpasswd -c $PATH
    }
}

Nginx 访问状态监控

## 举例说明
[root@web01 nginx]# cat nginx.conf
...
    location /status {
    stub_status on;
    access_log off;
    }
...

Nginx 索引功能

作用:将网站转化为类似ftp的站点,作为共享文件的工具;

[root@web01 nginx]# cat nginx.conf
...
    location /download {
        autoindex on;
    }
...

Nginx 目录别名

作用:将域名后缀的路径设置一个别名,通过多种方式访问;

#访问 www.bossx.club/dw == www.boosx.club/download 
[root@web01 nginx]# cat nginx.conf
...
    location /dw {
         alias /var/html/download;
    }
...
posted @ 2020-05-09 21:44  OneLpc  阅读(318)  评论(0编辑  收藏  举报