初识Nginx

摘要:最近几个项目中的接口总是访问受限,需要后端同事配置Nginx代理,了解下Nginx后面自己配置。     

        Nginx 是一款高性能的开源 Web 服务器和反向代理服务器。它具有轻量级、高并发、低内存消耗等特点,常被用作静态资源服务、负载均衡、反向代理和缓存等方面的解决方案。

        下面是 Nginx 的一些重要特点和主要用途:

  1. 高并发处理能力:Nginx 使用事件驱动的异步非阻塞架构,能够处理大量并发连接而不会因为连接数增加而导致性能下降。
  2. 轻量级:Nginx 的代码精简,占用的系统资源较少,启动速度快。
  3. 配置灵活简单:Nginx 的配置文件采用简洁的语法,易于理解和修改,支持动态加载配置。
  4. 静态资源服务:Nginx 可用于提供静态文件的服务,如 HTML、CSS、JavaScript、图片等。
  5. 反向代理:Nginx 可以作为反向代理,将客户端的请求转发到后端的多台服务器,实现负载均衡和高可用。
  6. 缓存加速:Nginx 可以缓存部分静态内容,提高访问速度。
  7. SSL/TLS 支持:Nginx 支持 SSL/TLS 协议,可以配置 HTTPS 服务,提供安全的数据传输。
  8. 动态模块支持:Nginx 支持第三方模块的插件扩展,可以根据需求加载相应的模块。

        Nginx 可以作为独立的 Web 服务器使用,也可以与其他应用服务器(如 Node.js、Tomcat 等)配合使用,通过反向代理实现负载均衡和高可用性。

官网: https://nginx.org/

1. Nginx的安装

1.1 Nginx 在CentOS安装

 1. 首先登录阿里云

# 登录阿里云
czh12@czh12deiMac ~ % ssh [email protected]
[email protected]'s password: 
Last failed login: Tue Jan 30 12:57:24 CST 2024 from 182.47.189.139 on ssh:notty
There were 79 failed login attempts since the last successful login.
Last login: Thu Jan 25 16:33:33 2024 from 39.144.157.59

Welcome to Alibaba Cloud Elastic Compute Service !

2. 安装yum包管理器

# 安装了yum包管理器
[root@izbp1fwu8k6txnl7pd2enpz ~]# sudo yum install yum-utils
已加载插件:fastestmirror
...

3. 配置Nginx的地址

# 配置Nginx的地址
# 打开配置文件
[root@izbp1fwu8k6txnl7pd2enpz ~]# vim /etc/yum.repos.d/nginx.repo
# 删除原有配置文件
[root@izbp1fwu8k6txnl7pd2enpz ~]# rm /etc/yum.repos.d/nginx.repo
rm:是否删除普通文件 "/etc/yum.repos.d/nginx.repo"?y
# 新配置文件中粘贴如下内容,并保存
[root@izbp1fwu8k6txnl7pd2enpz ~]# vim /etc/yum.repos.d/nginx.repo

# 新配置文件中粘贴的内容
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true


#######上述配置内容说明#######
这是一个Yum仓库的配置文件示例,其中定义了两个不同的仓库:nginx-stable 和 nginx-mainline。
[nginx-stable]:这是一个名为 nginx-stable 的仓库的配置部分。
name=nginx stable repo:指定了仓库的名称。
baseurl=http://nginx.org/packages/centos/7/$basearch/:指定了仓库的基本URL,即软件包的下载
地址。在此示例中,它指向Nginx稳定版本的CentOS 7软件包。
gpgcheck=1:启用GPG检查,以确保从该仓库下载的软件包是经过验证的。
enabled=1:启用该仓库,表示可以使用这个仓库中的软件包。
gpgkey=https://nginx.org/keys/nginx_signing.key:指定了GPG密钥的URL,用于验证软件包的完整性
和真实性。
module_hotfixes=true:启用模块热修复功能。
[nginx-mainline]:这是一个名为 nginx-mainline 的仓库的配置部分。
与 nginx-stable 类似,它指定了不同的 baseurl,并且 enabled 设置为 0,表示该仓库当前被禁用。
这意味着默认情况下,系统将使用 nginx-stable 仓库中的软件包。

这个配置文件允许你在系统上使用 yum 命令安装、更新和管理来自Nginx仓库的软件包。要使用这些仓库中的软件
包,你需要确保已安装了相应的GPG密钥,并且将 enabled 设置为 1(
或者你可以使用 yum --enablerepo=<仓库名称> 指定启用的仓库)

4. 查看源,Yum包管理器的系统上列出所有与 "nginx" 相关的软件包;

        yum list | grep nginx 具体而言,该命令执行以下操作:

        yum list:列出系统上可用的所有软件包;

         |:管道符号,将前一个命令的输出作为后一个命令的输入;

        grep nginx:使用grep命令过滤包含 "nginx" 字符串的行。

[root@izbp1fwu8k6txnl7pd2enpz ~]# yum list|grep nginx
nginx.x86_64                             1:1.25.3-1.el7.ngx            installed
collectd-nginx.x86_64                    5.8.1-1.el7                   epel     
lemonldap-ng-nginx.noarch                2.18.1-1.el7                  epel     
munin-nginx.noarch                       2.0.75-1.el7                  epel     
nginx-all-modules.noarch                 1:1.20.1-10.el7               epel     
nginx-debug.x86_64                       1:1.8.0-1.el7.ngx             nginx-stable
nginx-debuginfo.x86_64                   1:1.24.0-1.el7.ngx            nginx-stable
nginx-filesystem.noarch                  1:1.20.1-10.el7               epel     
nginx-mod-devel.x86_64                   1:1.20.1-10.el7               epel     
nginx-mod-http-image-filter.x86_64       1:1.20.1-10.el7               epel     
nginx-mod-http-perl.x86_64               1:1.20.1-10.el7               epel     
nginx-mod-http-xslt-filter.x86_64        1:1.20.1-10.el7               epel     
nginx-mod-mail.x86_64                    1:1.20.1-10.el7               epel     
nginx-mod-stream.x86_64                  1:1.20.1-10.el7               epel     
nginx-module-geoip.x86_64                1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-geoip-debuginfo.x86_64      1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-image-filter.x86_64         1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-image-filter-debuginfo.x86_64
                                         1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-njs.x86_64                  1:1.24.0+0.8.2-1.el7.ngx      nginx-stable
nginx-module-njs-debuginfo.x86_64        1:1.24.0+0.8.2-1.el7.ngx      nginx-stable
nginx-module-perl.x86_64                 1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-perl-debuginfo.x86_64       1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-xslt.x86_64                 1:1.24.0-1.el7.ngx            nginx-stable
nginx-module-xslt-debuginfo.x86_64       1:1.24.0-1.el7.ngx            nginx-stable
nginx-nr-agent.noarch                    2.0.0-12.el7.ngx              nginx-stable
pagure-web-nginx.noarch                  5.13.3-10.el7                 epel     
pcp-pmda-nginx.x86_64                    4.3.2-13.el7_9                updates  
python2-certbot-nginx.noarch             1.11.0-1.el7                  epel     
sympa-nginx.x86_64                       6.2.72-3.el7                  epel     
[root@izbp1fwu8k6txnl7pd2enpz ~]# yum install nginx
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
匹配 1:nginx-1.24.0-1.el7.ngx.x86_64 的软件包已经安装。正在检查更新。
无须任何处理

5. 查看版本验证是否安装成功

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -v
nginx version: nginx/1.25.3

6. 查看安装位置

[root@izbp1fwu8k6txnl7pd2enpz ~]# whereis nginx
nginx: /usr/sbin/nginx /usr/lib64/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz
1.2  MacOS 和Windows的安装

        MacOS中 安装homebrew,然后nginx使用安装brew:

$ brew install nginx

后续按提示安装即可,通常zoo.conf是直接配置好的。

        windows不推荐安装nginx,nginx不适合运行在Windows上,尽量运行在linux上。

2. Nginx 的常用命令

/usr/sbin/nginx : 启动Nginx

/usr/sbin/nginx

# 正常启动不会有反馈;重复启动会有绑定失败提示

nginx -h :帮助指令

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -h
nginx version: nginx/1.25.3
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /etc/nginx/)
  -e filename   : set error log file (default: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

nginx -c 配置文件 : 更换配置文件启动

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 相当于以这个配置文件重新启动
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -c /etc/nginx/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()

nginx -t : 测试配置文件,并查看在使用的配置文件是那个

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx -v : 查看版本

nginx -V: 查看版本V和配置信息

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -v
nginx version: nginx/1.25.3
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -V
nginx version: nginx/1.25.3
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 -s stop : 立即停止(强制);

nginx -s quit : 优雅停止,已经建立连接的会继续服务,直到退出;

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

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -s stop
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -s quit
nginx: [error] open() "/var/run/nginx.pid" failed (2: No such file or directory)
[root@izbp1fwu8k6txnl7pd2enpz ~]# /usr/sbin/nginx
[root@izbp1fwu8k6txnl7pd2enpz ~]# /usr/sbin/nginx
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@izbp1fwu8k6txnl7pd2enpz ~]# nginx -s quit
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@izbp1fwu8k6txnl7pd2enpz ~]# vim /etc/nginx/nginx.conf
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -t
nginx: [emerg] unknown directive "uuuser" in /etc/nginx/nginx.conf:2
nginx: configuration file /etc/nginx/nginx.conf test failed
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -s reload
nginx: [emerg] unknown directive "uuuser" in /etc/nginx/nginx.conf:2
[root@izbp1fwu8k6txnl7pd2enpz ~]# vim /etc/nginx/nginx.conf
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -s reload
nginx: [error] invalid PID number "" in "/var/run/nginx.pid"
[root@izbp1fwu8k6txnl7pd2enpz ~]# /usr/sbin/nginx
[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -s reload

3. 配置文件讲解

        使用nginx -t 找到配置文件位置,并打开配置文件。

[root@izbp1fwu8k6txnl7pd2enpz ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@izbp1fwu8k6txnl7pd2enpz ~]# cd /etc/nginx
[root@izbp1fwu8k6txnl7pd2enpz ~]# vim nginx.conf

        nginx.conf配置文件中主要的配置项讲解:

一些重要的配置项列举如下:

# 运行用户
user  nginx;
# 工作进程数,可以和CPU核心数一致,也可以设置为auto
worker_processes  1;
# 错误日志路径
error_log  /var/log/nginx/error.log;
pid      /run/nginx.pid;
# 把对应的配置文件导入
include /usr/share/nginx/modules/*.conf;
events {
# 连接数
    worker_connections  1024;
}
# http服务器的配置
http {
# 日志的格式
    log_format main '$remote_addr - $remote_user [$time_local]...'
# 访问日志
    access_log  /var/log/nginx/access.log  main;
# 是否开启高效的传输模式
    sendfile        on;
# keepalive超时时间
    keepalive_timeout  65;
#加载其他各模块的配置文件
include /etc/nginx/conf.d/*.conf;
    server {
#监听端口号
        listen       80;
        listen       [::]:80;
        server_name  _;
    #root路径的位置
        root         /usr/share/nginx/html2;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}

        需要注意Nginx并不是将所有配置写入一个文件,会在nginx.conf中使用include加载其他配置文件,例如,此处将加载/usr/share/nginx/modules/*目录下所有以.conf结尾的文件;如此可以实现多模块的配置,当同一个nginx服务于多个服务器,将不同服务器的配置文件单独配置后引入即可。

# 把对应的配置文件导入
include /usr/share/nginx/modules/*.conf;

4. 搭建静态资源服务器

        尝试使用Nginx搭建静态服务器,基本步骤如下:

1. 使用mkdir + 文件夹名称,在root路径的位置创建新的文件夹,用于存储静态文件;

2. 新开终端,使用scp命令上传文件到指定目录

# scp命令上传文件: scp [参数] [原路径] [目标路径]; 提示输入的密码是ECS的密码
czh12@czh12deiMac ~ % scp -r /Users/czh12/Learning/video/templatemo_560_astro_motion/. [email protected]:/usr/share/nginx/html2/
[email protected]'s password: 
watermark.jpg                                                     100%   52KB 301.5KB/s   00:00    
0c5adc4f-334c-4183-91b1-21276ee7a980.jpeg                         100%   13KB  78.9KB/s   00:00    
e566fb7c-c578-44dc-9541-7af868c42b67.jpeg                         100%   13KB  77.6KB/s   00:00    
new-xia.png ……  
## 注意此处上传多文件,但不希望重新创建原文件夹(templatemo_560_astro_motion),需要在文件夹后加  **/.**  ; 表示上传其中的所有文件
```

3. 修改配置文件nginx.conf;将root路径的位置配置成上述新建文件夹;在使用nginx -s reload重nginx

你可能感兴趣的:(初入后端,nginx,运维,后端)