Nginx基本简介
发布日期:2021-05-08 03:57:37 浏览次数:25 分类:精选文章

本文共 16261 字,大约阅读时间需要 54 分钟。

Nginx基本简述

Nginx是一个开源且高性能,可靠的Http Web服务、代理服务。

  1. 开源: 直接获取源代码
  2. 高性能: 支持海量并发
  3. 可靠: 服务稳定

我们为什么选择Nginx服务

Nginx非常轻量

  1. 功能模块少(源代码仅保留http与核心模块代码,其余不够核心代码会作为插件来安装)
  2. 代码模块化(易读,便于二次开发,对于开发人员是非常友好的)

互联网公司都选择Nginx

  1. Nginx技术成熟,具备的功能是企业最常使用而且最需要的
  2. 适合当前主流架构趋势,微服务,云架构,中间层
  3. 统一技术栈,降低维护成本,降低技术更新成本

Nginx采用Epool网络模型,Apache采用Select模型

  • Select: 当用户发起一次请求,select模型就会进行一次遍历扫描,从而导致性能低下。
  • Epool: 当用户发起请求,epool模型会直接进行处理,效率高效,并无连接限制。

Nginx 经典应用场景

在这里插入图片描述

  • 开源的Web服务器
- 静态资源nginxapacheIISlighttpdtengineopenresty- 动态资源TomcatJboosresin

Nginx安装

  • nginx官网 : http://nginx.org/

方式一: yum安装(最好使用官方的源,epel源安装的nginx配置文件内容比较乱)

1. 添加nginx的官方源vim /etc/yum.repos.d/nginx.repo[nginx-stable]name=nginx stable repobaseurl=http://nginx.org/packages/centos/$releasever/$basearch/gpgcheck=1enabled=1gpgkey=https://nginx.org/keys/nginx_signing.keymodule_hotfixes=true[nginx-mainline]name=nginx mainline repobaseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/gpgcheck=1enabled=0gpgkey=https://nginx.org/keys/nginx_signing.keymodule_hotfixes=true2. 下载nginx软件yum -y install nginx3. 查看nginx版本nginx -v# nginx version: nginx/1.20.0- 查看nginx当前的参数nginx -V# nginx version: nginx/1.20.0# built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) # built with OpenSSL 1.0.2k-fips  26 Jan 2017# TLS SNI support enabled# configure arguments: --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'

方式二: 源码编译安装(按照nginx指定的参数进行源码包编译安装)

1. 下载源码包wget http://nginx.org/download/nginx-1.20.0.tar.gz2. 解压nginx源码包tar -xf nginx-1.20.0.tar.gz 3. 编译前系统检查cd nginx-1.20.0/./configure 		(后面跟--prefix=/etc/nginx...  nginx当前的参数,如果没有需求跟指定的nginx参数的话,直接使用命令即可)# ./configure: error: the HTTP rewrite module requires the PCRE library.4. 安装进行编译时所缺少的库yum install pcre pcre-devel -y5. 编译前系统检查./configure 		(后面跟--prefix=/etc/nginx...  nginx当前的参数,如果没有需求跟指定的nginx参数的话,直接使用命令即可)# ./configure: error: SSL modules require the OpenSSL library.6. 安装进行编译时所缺少的库yum -y install openssl openssl-devel7. 第三次进行系统检查./configure 		(后面跟--prefix=/etc/nginx...  nginx当前的参数,如果没有需求跟指定的nginx参数的话,直接使用命令即可)# 没有出现报错8. 开始进行编译并安装make && make install			9. 运行nginx/usr/local/nginx/sbin/nginx# 我们安装完成后,可以打开浏览器,输入虚拟机的IP。如果显示出Welcome to nginx!那就是代表安装完成。10. 添加环境变量vim /root/.bash_profile 				添加服务器系统的环境变量NGINX_HOME=/usr/local/nginx/sbin		PATH=$PATH:$NGINX_HOMEexport PATHsource /root/.bash_profile				重载root用户系统的环境变量# 加载完环境变量之后,执行nginx,就不需要再加文件路径了

nginx启动与停止的两种方式

方式一(适用于源码编译安装):nginx 							启动nginx -s stop					停止nginx -s restart/reload			重启方式二(适用于yum安装):systemctl start nginx			启动	systemctl restart nginx			重启systemctl stop nginx			停止注意: 建议不要混合使用这两种方式,如果我们使用第一种方式启动nginx,那么是无法使用第二种方式进行管理的。

nginx目录结构

rpm -ql nginx 					查看nginx的目录结构/etc/logrotate.d/nginx			日志轮转/etc/nginx						默认的配置文件/etc/nginx/conf.d/etc/nginx/conf.d/default.conf/etc/nginx/fastcgi_params/etc/nginx/mime.types			存放静态资源的关系映射文件/etc/nginx/modules				模块/etc/nginx/nginx.conf			主配置文件/etc/nginx/scgi_params			/etc/nginx/uwsgi_params/usr/lib/systemd/system/nginx-debug.service/usr/lib/systemd/system/nginx.service/usr/lib64/nginx/usr/lib64/nginx/modules/usr/libexec/initscripts/legacy-actions/nginx/usr/libexec/initscripts/legacy-actions/nginx/check-reload/usr/libexec/initscripts/legacy-actions/nginx/upgrade/usr/sbin/nginx					nginx命令执行文件/usr/sbin/nginx-debug/usr/share/doc/nginx-1.20.0/usr/share/doc/nginx-1.20.0/COPYRIGHT/usr/share/man/man8/nginx.8.gz/usr/share/nginx				默认的网站页面/usr/share/nginx/html/usr/share/nginx/html/50x.html/usr/share/nginx/html/index.html/var/cache/nginx				缓存	/var/log/nginx					日志

Nginx配置文件

  • Nginx主配置文件/etc/nginx/nginx.conf是一个纯文本类型的文件,整个配置文件是以区块的形式组织的。每一个区块以一对大括号{}来表示开始与结束。
  • Nginx主配置文件整体分为三块,分别是CoreModule(核心模块),EventModule(事件驱动模块),HttpCoreModule(http内核模块)。
- 主配置文件vim /etc/nginx/nginx.conf======================================核心模块==========================================user  nginx;									nginx进程运行的用户worker_processes  auto;							nginx工作的进程数量(辅助进程自动)error_log  /var/log/nginx/error.log notice;		nginx的错误日志【警告类型及其警告以上的都记录】pid        /var/run/nginx.pid;					nginx进程运行后的进程id======================================事件模块==========================================events {       worker_connections  1024;					一个work进程的最大连接数	use epool;									使用epool的网络模型}===================================http核心层模块=========================================http {       include       /etc/nginx/mime.types;				包含资源类型文件    default_type  application/octet-stream;			默认以下载方式传输给浏览器(前提是该资源在/etc/nginx/mime.types中无法找到)			日志格式定义    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  /var/log/nginx/access.log  main;		访问日志    sendfile        on;							高效传输文件的方式    #tcp_nopush     on;    keepalive_timeout  65;						长连接的超时时间    #gzip  on;									是否开启压缩功能    include /etc/nginx/conf.d/*.conf;			包含目录下的*.conf文件	}- 主配置文件中定义的局部配置文件vim /etc/nginx/conf.d/default.conf				   server {   								定义一个网站    listen       80;					监听端口    server_name  localhost;				域名	    #access_log  /var/log/nginx/host.access.log  main;		访问日志(default.conf下的日志文件优先级高于Nginx主配置文件中的日志文件)    location / {   								位置		        root   /usr/share/nginx/html;			代码的主文件位置        index  index.html index.htm;			服务端默认返回给用户的文件		    }}- http server location扩展了解项http{   }层下允许有多个server{   }层,一个server{   }层下又允许有多个location。http{   }标签主要用来解决用户的请求与响应。server{   }标签主要用来响应具体的某一个网站。location{   }标签主要用于匹配网站具体URL路径。

Nginx搭建一个静态资源Web服务器

  1. 编写Nginx配置文件
vim /etc/nginx/conf.d/game.conf server {           listen 80;        server_name game.nana.com;        location / {                   root /code;                index index.html index.html;        }}
  1. 根据配置文件,创建目录,上传代码
mkdir /codecd /code上传一个游戏包到/code目录下(rz -E   游戏包html.zip)unzip 游戏包html.zip				# 将压缩包解压到/code目录下
  1. 重启nginx服务
方式一:systemctl restart nginx				立即重启,强制重启方式二:systemctl reload nginx				平滑重启(等待交互完成之后再重启)
  1. 配置域名解析
windows用户:C:\Windows\System32\drivers\etc打开hosts文件,添加:192.168.15.7	game.nana.com	Mac用户:sudo vim /etc/hosts打开hosts文件,添加:192.168.15.7	game.nana.com	- 检查域名解析的ip是否是192.168.15.7打开cmd,输入C:\Users\彭于晏>ping game.nana.com		# 正在 Ping game.nana.com [192.168.15.7] 具有 32 字节的数据:# 来自 192.168.15.7 的回复: 字节=32 时间<1ms TTL=64# 来自 192.168.15.7 的回复: 字节=32 时间<1ms TTL=64# 来自 192.168.15.7 的回复: 字节=32 时间<1ms TTL=64# 来自 192.168.15.7 的回复: 字节=32 时间<1ms TTL=64# 192.168.15.7 的 Ping 统计信息:#    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),# 往返行程的估计时间(以毫秒为单位):#    最短 = 0ms,最长 = 0ms,平均 = 0ms
  1. 通过浏览器访问对应的项目
打开浏览器输入:	game.nana.com如果可以成功访问到游戏页面就表示nginx搭建成功了

Nginx配置虚拟主机有如下三种方式

方式一: 基于主机多IP方式

方式二: 基于端口的配置方式
方式三: 基于多个hosts名称方式(多域名方式)

基于主机多IP方式

http://1.1.1.1  ------> ip 1.1.1.1 -------> 虚拟主机Ahttp://1.1.1.2  ------> ip 1.1.1.2 -------> 虚拟主机Bhttp://1.1.1.3  ------> ip 1.1.1.3 -------> 虚拟主机C一个域名对应一个IP地址,一个IP地址对应一个网卡
  • 基于多IP的方式,有如下两种方式
方式一、多个网卡多IP的方式:网卡1 <----------> ip1(1.1.1.1)网卡2 <----------> ip2(1.1.1.2)方式二、单网卡多IP的方式:网卡1 <----------> ip1(1.1.1.1)网卡1 <----------> ip2(1.1.1.2)
  • 方式一: 多个网卡多IP的虚拟主机配置方式:
1.  编写Nginx配置文件vim /etc/nginx/conf.d/ip.confserver {           listen 172.16.1.7:80;        server_name _;        location / {                   root /code_ip_eth0;                index index.html;        }}server {           listen 192.168.15.7:80;        server_name _;        location / {                   root /code_ip_eth1;                index index.html;        }}2. 根据配置文件,创建目录mkdir /code_ip_eth0echo eth0 > /code_ip_eth0/index.html mkdir /code_ip_eth1echo eth1 > /code_ip_eth1/index.html3. 重启nginx服务nginx -t				检查nginx语法是否错误# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok# nginx: configuration file /etc/nginx/nginx.conf test is successfulsystemctl restart nginx4. 使用curl命令测试curl 172.16.1.7# eth0curl 192.168.15.7# eth1
  • 方式二: 单个网卡多IP的虚拟主机配置方式:
1. 给eth0网卡添加一个ipip addr add 172.16.1.8/24 dev eth02. 编写Nginx配置文件vim /etc/nginx/conf.d/ip01.confserver {           listen 172.16.1.8:80;        server_name _;        location / {                   root /code_ip_eth0;                index index.html;        }}vim /etc/nginx/conf.d/ip02.confserver {           listen 192.168.15.7:80;        server_name _;        location / {                   root /code_ip_eth1;                index index.html;        }}3. 根据配置文件,创建目录mkdir /code_ip_eth0echo Eth0 > /code_ip_eth0/index.html mkdir /code_ip_eth1echo Eth1 > /code_ip_eth1/index.html4. 重启nginx服务nginx -t				检查nginx主配置文件语法是否错误# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok# nginx: configuration file /etc/nginx/nginx.conf test is successfulsystemctl restart nginx5. 使用curl命令测试curl 172.16.1.8# Eth0curl 192.168.15.7# Eth1

基于端口的配置方式 (适用于企业内部)

http://1.1.1.1:80  ------> Listen:80 -------> 虚拟主机Ahttp://1.1.1.1:81  ------> Listen:81 -------> 虚拟主机Bhttp://1.1.1.1:82  ------> Listen:82 -------> 虚拟主机C同一个ip,端口不一致,不同的端口对应不同的项目
  • 基于端口的配置方式
1. 编写Nginx配置文件vim /etc/nginx/conf.d/port.confserver {           listen 81;        location / {                   root /code_81;                index index.html;        }}server {           listen 82;        location / {                   root /code_82;                index index.html;        }}2. 根据配置文件,创建目录mkdir /code_{   81..82}echo 81 > /code_81/index.html echo 82 > /code_82/index.html3. 重启nginx服务nginx -t				检查nginx主配置文件语法是否错误# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok# nginx: configuration file /etc/nginx/nginx.conf test is successfulsystemctl restart nginx			4. 使用curl命令测试curl 192.168.15.7:81# 81curl 192.168.15.7:82# 82注意:如果我们在Nginx配置文件中没有指定ip,那么该服务器中的所有ip地址只要加上对应的端口号,都是可以访问到配置文件中对应文件中的内容的。

基于多个hosts名称方式(多域名方式)

http://1.nana.com  ------> 1.nana.com -------> 虚拟主机Ahttp://2.nana.com  ------> 2.nana.com -------> 虚拟主机Bhttp://3.nana.com  ------> 3.nana.com -------> 虚拟主机C基于多个域名,一台服务器,不同的域名访问不同的项目
  • 基于多域名的配置方式
cd /etc/nginx/conf.d1. 编写Nginx配置文件vim test01.nana.com.confserver {           listen 80;        server_name test01.nana.com;        location / {                   root /code/test01;                index index.html;        }}vim test02.nana.com.confserver {           listen 80;        server_name test02.nana.com;        location / {                   root /code/test02;                index index.html;        }}2. 根据配置文件,创建目录mkdir -p /code/test{   01..02}echo test01_server > /code/test01/index.htmlecho test02_server > /code/test02/index.html3. 重启nginx服务nginx -t				检查nginx主配置文件语法是否错误# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok# nginx: configuration file /etc/nginx/nginx.conf test is successfulsystemctl restart nginx4. 配置域名解析windows用户:C:\Windows\System32\drivers\etc打开hosts文件,添加:192.168.15.7		test01.nana.com192.168.15.7		test02.nana.com- 检查域名解析的ip是否是192.168.15.7打开cmd,输入C:\Users\彭于晏>ping test01.nana.comC:\Users\彭于晏>ping test02.nana.com5. 通过浏览器访问该网站http://test01.nana.com/  --访问结果-->  test01_serverhttp://test02.nana.com/  --访问结果-->  test02_server
  • 我们将域名解析文件(C:\Windows\System32\drivers\etc)中的192.168.15.7 test02.nana.com修改成192.168.15.7 test03.nana.com,我们通过浏览器去访问test03.nana.com,发现访问的结果为test01_server,访问的域名和网页内容不匹配(域名和ip地址没有对应)。
    在这里插入图片描述

Nginx报错排查

  1. 修改完配置文件,记得使用nginx -t检查语法。
  2. 如果没有检查语法,直接重载导致报错。使用命令systemctl status nginx.server -l / journalctl -xe 进行排错。

Nginx日志

  • Nginx有非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志。日志格式通过log_format命令定义格式。

log_format定义日志格式语法

# 配置语法: 包括 error.log 	 access.logSyntax(语法): log_format name [escape=default/json] string ...;Default(违约): log_format combined "...";Context(上下文): http

默认Nginx定义的访问日志语法格式如下

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

Nginx日志格式允许包含的内置变量

$remote_addr 			记录客户端IP地址  $remote_user			记录客户端用户名$time_local				记录通用的本地时间$time_iso8601			记录ISO8601标准格式下的本地时间$request				记录请求的方法以及请求的http协议$status					记录请求的状态码(用于定位错误信息)$body_bytes_sent		发送给客户端的资源字节数,不包响应头的大小$msec					日志写入时间。单位为秒,精度是毫秒$http_referer			记录从哪个页面链接访问过来的$http_user_agent		记录客户端浏览器相关信息$http_x_forwarded_for	记录客户端IP地址$request_length			请求的长度(包括请求行,请求头和请求正文)	$request_time			请求花费的时间,单位为秒,精度为毫秒注:如果Nginx位于负载均衡器,nginx反向代理之后,为服务器无法直接获取客户端的真实IP地址。$remote_addr获取的是反向代理的IP地址。反向代理服务器在转发请求的http头信息中。增加x-forwarded-for信息,用来记录客户端IP地址和客户端请求的服务器地址。
  • 修改主配置文件访问日志的格式,进行测试
vim /etc/nginx/nginx.confhttp {       include       /etc/nginx/mime.types;    default_type  application/octet-stream;	log_format  ttt  '$remote_addr - $remote_user [$time_local] "$request" '	                  '$status $body_bytes_sent "$http_referer" "$request_time"';		access_log  /var/log/nginx/access.log  ttt;我们刷新http://test01.nana.com/浏览器页面做测试,tail -1 /var/log/nginx/access.log# 192.168.15.1 - - [06/May/2021:15:48:56 +0800] "GET / HTTP/1.1" 200 14 "-" "0.000"

Nginx访问日志与错误日志

访问日志(默认访问日志路径/var/log/nginx/access.log)

  • 如果在http层配置了access_log,在server层没有配置,那么所有的server日志都写入http层。
  • 如果在http层和server层都配置了access_log,那么所有的server日志都写入server层。
  • server层日志写入的优先级高于http层。

在server层配置access_log做访问测试

1. 将当前的server网站的访问日志记录至对应的目录,使用main格式vim test01.nana.com.conf server {           listen 80;        server_name test01.nana.com;        access_log /var/log/nginx/test01.log main;		# 日志目录存在,那么记录日志的文件会自动创建		        location / {                   root /code/test01;                index index.html;        }        #		 当有人请求改favicon.ico时,不记录日志	#        location /favicon.ico {   #                access_log off;#                return 200;#        }}2. 重启服务nginx -tsystemctl restart nginx- 在浏览器清空缓存重载http://test01.nana.com/,查看日志文件下的内容ls /var/log/nginx/# access.log  error.log  test01.logtail -f /var/log/nginx/test01.log# 192.168.15.1 - - [06/May/2021:16:25:46 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 Edg/90.0.818.51" "-"

错误日志(默认错误日志路径/var/log/nginx/error.log)

我们在访问请求中的报错,要查看错误日志的报错进行排错

- 模拟访问请求报错(1):我们在浏览器中故意输错域名: http://test01.nana.com/xxx查看错误日志报错信息tail -f /var/log/nginx/error.log# 2021/05/06 16:44:47 [error] 2882#2882: *1 open() "/code/test01/xxx" failed (2: No such file or directory), client: 192.168.15.1, server: test01.nana.com, request: "GET /xxx HTTP/1.1", host: "test01.nana.com"- 模拟访问请求报错(2):我们将server层中指定的文件index.html,文件名故意改成index.htmcd /code/test01/mv index.html index.htm 查看错误日志报错信息tail -f /var/log/nginx/error.log# 2021/05/06 16:48:55 [error] 2882#2882: *5 directory index of "/code/test01/" is forbidden, client: 192.168.15.1, server: test01.nana.com, request: "GET / HTTP/1.1", host: "test01.nana.com"

日志的切割logrotate

  • 日志的记录如果一直记录在一个日志文件中,随着时间的推移,日志文件会变得越来越大,可能会导致日志文件无法查看。为了解决这个问题,nginx服务自带了日志切割(logrotate)的功能。
  • 源码编译可能会需要自己去写脚本,yum安装nginx会自带日志自动切割功能。
- 查看日志切割默认的配置文件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					# mv access.log --> access.log-20210506.gz	                        kill -USR1 `cat /var/run/nginx.pid`			# 发送信号,切割好之后重新加载日志文件                fi        endscript}
上一篇:端口列表_端口占用问题解决kill_ps_net
下一篇:python_时间序列_重采样及频率转换

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月13日 14时56分29秒