nginx学习笔记

1、什么是nginx

  ①nginx是一个高性能的、轻量级的http和反向代理的服务器,提供了IMAP、POP3、SMTP的服务
  ②因其稳定,高性能,高吞吐、简单的配置实现丰富的功能而闻名
  ③nginx占用的系统资源非常少,能做到事情却非常多,能够优雅的解决很多问题

 

2、nginx能做什么

  ①nginx通常用于反向代理
  ②前端跨域问题解决
  ③动静分离,因为nginx处理静态资源非常牛逼,但是处理动态资源就比较鸡肋了
  ④负载均衡,系统庞大之后,后端通常会分布式部署,nginx可以按一定的负载均衡策略访问后端的服务
  ⑤作为邮件代理服务器

 

3、安装nginx(linux下)

  ①安装编译环境和库文件

yum -y install make 
yum -y install zlib zlib-devel
yum -y install gcc-c++
yum -y install libtool
yum -y install openssl openssl-devel
yum -y install pcre pcre-devel

  

  ②下载源码安装包(PCRE版本),PCRE版本支持正则、rewirte等功能
    网址:http://nginx.org/en/download.html

 

  ③上传tar.gz源码包,进行解压

# 解压源码包
tar  -zxvf  /opt/nginx-1.22.tar.gz  

# 进入解压目录
cd ./nginx-1.22

# 运行配置文件,安装nginx到指定目录
./configure --prefix=/usr/local/ngixn/ 

# 编译安装
make && make install  

 

  ④进入安装目录,启动nginx,看到nginx默认首页即安装成功

# 进入启动目录
cd /usr/local/ngixn/sbin

# 运行启动nginx命令
./nginx

  

注意:centos默认不会开启端口,如果访问失败,请确认端口是否开启

# 两种方案,如果是自己测试,可以直接关闭防火墙,一劳永逸
# 如果是线上项目或比较重要的环境,不可关闭,只能开启端口

# 查看防火墙状态
systemctl  status  firewalld.service

#开启防火墙
systemctl  start  firewalld.service

# 关闭防火墙
systemctl  stop  firewalld.service
# 再运行下面命令可永久关闭(开机不会自启动)
systemctl  disable  firewalld.service
# 开启某个端口步骤
sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --add-port=80/tcp --permanent
sudo firewall-cmd --reload
# 注:--permanent 表示永久有效,否则的话重启配置会失效

 

4、常用命令

# 开启nginx
nginx

# 强制关闭nginx
nginx  -s  stop

# 优雅关闭nginx
nginx  -s  quit

# 重新加载nginx配置文件
nginx  -s  reload

# 重新打开nginx日志文件
nginx  -s  reopen

#杀死所有nginx进程
killall nginx 

# 显示nginx版本号
nginx  -v
nginx  -V

 

5、配置文件详解

#user  nobody;   #定义nginx运行的用户和用户组
worker_processes  1;  # nginx工作线程数,建议设置为CPU的总核数

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;   # 全局错误日志定义类型,有这么几个等级 【debug | info | notice | warn | error | crit】

#pid        logs/nginx.pid;  # 进程的pid文件

# event全局块
events {
   accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数,默认为512
}

# http块
http {
    include       mime.types;   # 文件扩展名与文件类型映射
    default_type  application/octet-stream;  # 默认文件类型,默认为text/plain

    #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 off; 取消服务日志
#access_log logs
/access.log main; sendfile on; # 允许sendfile方式传输文件
#sendfile_max_chunk 100k;#每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
#tcp_nopush on; #keepalive_timeout
0; keepalive_timeout 65; # 连接超时时间,默认为75s,可以在http,server,location块。

upstream myserver {
    server 192.168.80.131:8080;
    server 192.168.80.133:8080;
    #server 192.168.80.133:8080 backup; # 热备
} #
gzip on; server {
#keepalive_requests 120;#单连接请求上限次数。
listen
80; # 监听端口 server_name 192.168.80.154; # 监听主机 #charset koi8-r; #access_log logs/host.access.log main; location / { # 请求的url过滤(可以设置正则) #root html; # 根目录 #index index.html index.htm; # 默认首页
proxy_pass http://myserver; # 转到负载均衡列表
deny 192.168.80.100; # 拒绝的ip
allow 192.168.80.200; # 允许的ip } #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; # } #} }
几个常见配置项了解一下:
1.$remote_addr 与 $http_x_forwarded_for 用以记录客户端的ip地址;
2.$remote_user :用来记录客户端用户名称;
3.$time_local : 用来记录访问时间与时区;
4.$request : 用来记录请求的url与http协议;
5.$status : 用来记录请求状态;成功是200;
6.$body_bytes_s ent :记录发送给客户端文件主体内容大小;
7.$http_referer :用来记录从那个页面链接访问过来的;
8.$http_user_agent :记录客户端浏览器的相关信息;
# location中正则的用法

= 开头表示精确匹配
如 A 中只匹配根目录结尾的请求,后面不能带任何字符串。

^~ 开头表示uri以某个常规字符串开头,不是正则匹配

~ 开头表示区分大小写的正则匹配;

~* 开头表示不区分大小写的正则匹配

/ 通用匹配, 如果没有其它匹配,任何请求都会匹配到,考虑放在最后



location  = / {
  # 精确匹配 / ,主机名后面不能带任何字符串
  [ configuration A ] 
}
 
location  / {
  # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
  # 但是正则和最长字符串会优先匹配
  [ configuration B ] 
}
 
location /documents/ {
  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration C ] 
}
 
location ~ /documents/Abc {
  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration CC ] 
}
 
location ^~ /images/ {
  # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。
  [ configuration D ] 
}
 
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配所有以 gif,jpg或jpeg 结尾的请求
  # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则
  [ configuration E ] 
}
 
location /images/ {
  # 字符匹配到 /images/,继续往下,会发现 ^~ 存在
  [ configuration F ] 
}
 
location /images/abc {
  # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在
  # F与G的放置顺序是没有关系的
  [ configuration G ] 
}
 
location ~ /images/abc/ {
  # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用
    [ configuration H ] 
}
 
location ~* /js/.*/\.js



上面的匹配结果
按照上面的location写法,以下的匹配示例成立:

/ -> config A
精确完全匹配,即使/index.html也匹配不了

/downloads/download.html -> config B
匹配B以后,往下没有任何匹配,采用B

/images/1.gif -> configuration D
匹配到F,往下匹配到D,停止往下

/images/abc/def -> config D
最长匹配到G,往下匹配D,停止往下
你可以看到 任何以/images/开头的都会匹配到D并停止,FG写在这里是没有任何意义的,H是永远轮不到的,这里只是为了说明匹配顺序

/documents/document.html -> config C
匹配到C,往下没有任何匹配,采用C

/documents/1.jpg -> configuration E
匹配到C,往下正则匹配到E

/documents/Abc.jpg -> config CC
最长匹配到C,往下正则顺序匹配到CC,不会往下到E


#实际使用中的个人建议
#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。
#这里是直接转发给后端应用服务器了,也可以是一个静态首页
# 第一个必选规则
location = / {
    proxy_pass http://tomcat:8080/index
}
# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了
location / {
    proxy_pass http://tomcat:8080/
}

扩展:什么是惊群现象?

  一个网络连接过来,多个睡眠的进程被同时唤醒,但是只有一个进程去获得连接处理请求,这会严重影响系统的性能。

 

6、配置文件实现各个功能

  ①反向代理

# 反向代理实践1:按访问的不同路径,代理到不同的服务器,
# 访问192.168.80.134:80/student/.....时请求192.168.80.131:8080.
# 访问192.168.80.134:80/teacher/.....时请求192.168.80.132:8080.

# 具体配置
server {
        listen       80;   #监听端口
        server_name  192.168.80.134;   #监听地址     
  
        location  ~* /student/ {
           proxy_pass  192.168.80.131:8080;         
        }

        location  ~* /teacher/ {
           proxy_pass  192.168.80.132:8080;         
        }
    }

 

  ②负载均衡

# 方向代理负载均衡实践
# 当访问
192.168.80.134:80时,【轮询 / 权重 / iphash】的策略代理到192.168.80.131:8080 和 192.168.80.132:8080上

# 具体配置
upstream myserver { server
192.168.80.131:8080; server 192.168.80.132:8080; #server 192.168.80.131:8080 weight=80; #server 192.168.80.132:8080 weight=20; #ip_hash; } server { listen 80; #监听端口 server_name 192.168.80.134; #监听地址 location / { proxy_pass myserver ; } }

 

  ③动静分离

# nginx处理静态资源非常牛逼,所以实际使用中通常会做动静分离

# 静态资源(css / js / html / 图片等)存放在 /opt/static/目录下
# 图片放在 /opt/static/images/下
# css放在  /opt/static/css 下
# 前端服务器
192.168.80.131:80 # 后端服务器 192.168.80.132:8080 # 静态资源服务器 192.168.80.133:80

# 具体配置 server { listen 80; server_name 192.168.80.131; #charset koi8-r; #access_log logs/host.access.log main; #前端 location / { proxy_pass http://192.168.80.131:80; root html; index index.html index.htm; } #后端 location /api/ { proxy_pass http://192.168.80.132:8080; root html; index index.html index.htm; } #静态 location /static/ { alias /opt/static/
; autoindex on; } }
# root 和 alias 的区别

location  /movie {
      alias F:/迅雷下载/;
}

location /movie {
      root   F:/迅雷下载;
}

# alias 在实际访问中,http://127.0.0.1/movie/西游记.mp4    即是在访问  F:/迅雷下载/西游记.mp4

# root  在实际访问中,http://127.0.0.1/movie/西游记.mp4    即是在访问  F:/迅雷下载/movie/西游记.mp4 .

# alias 只能作用在location中,而root可以存在server、http和location中。

# alias 后面必须要用 “/” 结束,否则会找不到下一级目录的文件,而 root 则对 ”/” 可有可无

  

  ⑤前端跨域处理

# nginx实现跨域处理
# 有如下场景:
# 我们在开发一个vue应用时,要调用一些接口,但是页面和接口在不同的域,此时,我们可以使用nginx进行如下处理:

# vue页面所在  192.168.80.131:8080
# 要请求接口 http://192.168.80.133:8080/api/student/getById

# 处理思想:
# 第一步:如果接口在 http://192.168.80.131:8080/api/student/getById就好了,这样就不跨域了

# 第二步:nginx配置
server{
        listen 8888;
        server_name  192.168.80.131;
 
        location /{
            proxy_pass http://192.168.80.131:8080;
        }
 
        location /api{
            proxy_pass http://192.168.80.133:8080;
        }
    }

# 此处切记不可直接监听8080端口,直接监听的话会占用掉8080端口,导致本域的8080端口的前端页面不可调用了

 

 

7、nginx实现高可用(集群部署)------后续补充

posted @ 2022-08-12 17:24  手可摘星陈1024  阅读(130)  评论(0编辑  收藏  举报