linux centos 7 安装配置nginx

nginx安装

yum安装

如果简单使用yum安装最方便,如果需要定制,源码安装方便。

安装的先决条件

    sudo yum install yum-utils

yum-utils是一款由CentOS官方开发的Linux包管理工具,它是yum软件包管理器的扩展,提供了一系列额外的命令和脚本,可以帮助Linux系统管理员更好地管理依赖关系、配置文件、软件包更新等方面的工作。yum-utils提供了很多有用的工具,比如yum-builddep、yum-complete-transaction和yumdownloader等,在Linux系统管理中发挥了至关重要的作用。

gdb
find-repos-of-install

package-cleanup

repo-graph

repoclosure

repomanage

repoquery

yum-debug-dump  zless  yum-debug-restore

yumdownloader

reposync 

添加yum源

执行以下命令,添加Nginx到yum源。

sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

[root@localhost ~]# sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
获取http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
警告:/var/tmp/rpm-tmp.otJEV4: 头V4 RSA/SHA1 Signature, 密钥 ID 7bd9bf62: NOKEY
准备中...                          ################################# [100%]
正在升级/安装...
   1:nginx-release-centos-7-0.el7.ngx ################################# [100%]

   

添加完之后,执行以下命令,查看是否已经添加成功。

yum search nginx

默认情况下,这个源使用nginx的稳定包。如果想使用主流的安装包,运行以下命令:

sudo yum-config-manager --enable nginx-mainline

安装nginx

安装 nginx,运行以下命令:

    sudo yum install nginx

When prompted to accept the GPG key, verify that the fingerprint matches 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62, and if so, accept it.
安装后查看nginx是否正常启动,如果出现下面情况,端口被占用,重启下主机。

[root@gsl371 ~]# systemctl status nginx
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-06-21 11:43:54 CST; 3h 9min ago
     Docs: http://nginx.org/en/docs/
  Process: 3810 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=1/FAILURE)

Jun 21 11:43:51 gsl371 nginx[3810]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Jun 21 11:43:52 gsl371 nginx[3810]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Jun 21 11:43:52 gsl371 nginx[3810]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Jun 21 11:43:53 gsl371 nginx[3810]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Jun 21 11:43:53 gsl371 nginx[3810]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
Jun 21 11:43:54 gsl371 nginx[3810]: nginx: [emerg] still could not bind()
Jun 21 11:43:54 gsl371 systemd[1]: nginx.service: control process exited, code=exited status=1
Jun 21 11:43:54 gsl371 systemd[1]: Failed to start nginx - high performance web server.
Jun 21 11:43:54 gsl371 systemd[1]: Unit nginx.service entered failed state.
Jun 21 11:43:54 gsl371 systemd[1]: nginx.service failed.

如果仍然被占用,可通过查看端口命令找到被占用的端口,杀死相应的进程。
正常如下

[root@gsl371 ~]# systemctl status nginx
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2019-06-21 15:07:08 CST; 54s ago
     Docs: http://nginx.org/en/docs/
  Process: 2220 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 2221 (nginx)
   CGroup: /system.slice/nginx.service
           ├─2221 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─2222 nginx: worker process

Jun 21 15:07:08 gsl371 systemd[1]: Starting nginx - high performance web server...
Jun 21 15:07:08 gsl371 systemd[1]: Started nginx - high performance web server.

放通80端口,打开对应网址,出现欢迎界面,安装成功。
在这里插入图片描述

源码安装

安装编译需要工具和依赖:

yum install -y gcc gcc-c++ pcre-devel openssl-devel wget

一般我们都需要先装pcre, zlib,前者为了重写rewrite,后者为了gzip压缩。
1.选定源码下载目录
可以是任何目录,本文选定的是/root

cd /root

2、安装patch工具

yum install patch

安装https正向代理支持模块

如果不做https正向代理,可以跳过此步骤
下载地址:https://codeload.github.com/chobits/ngx_http_proxy_connect_module/zip/refs/heads/master
选择正确版本使用
在这里插入图片描述

unzip  ngx_http_proxy_connect_module-master.zip
mv ngx_http_proxy_connect_module-master ngx_http_proxy_connect_module
#文件在root目录
pwd
/root

下载nginx

Nginx 一般有两个版本,分别是稳定版和开发版,您可以根据您的目的来选择这两个版本的其中一个,下面是把 Nginx 安装到 /usr/local/nginx 目录下的详细步骤:

wget http://nginx.org/download/nginx-1.24.0.tar.gz

tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

打https支持补丁


cd /root/nginx-1.24.0

 pwd
/root/nginx-1.24.0


patch -p1 < /root/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite_102101.patch  #模块所在路径
patching file src/http/ngx_http_core_module.c
patching file src/http/ngx_http_parse.c
patching file src/http/ngx_http_request.c
Hunk #1 succeeded at 1100 (offset -2 lines).
Hunk #2 succeeded at 1744 (offset -2 lines).
Hunk #3 succeeded at 2047 (offset -26 lines).
patching file src/http/ngx_http_request.h
Hunk #1 succeeded at 416 (offset 2 lines).
patching file src/http/ngx_http_variables.c


编译安装nginx


./configure --prefix=/usr/local/nginx/ --add-module=/root/ngx_http_proxy_connect_module 

make 
make install

–prefix=/usr/local/nginx/ 指定安装后目录。
–add-module=/root/ngx_http_proxy_connect_module 指定添加https支持模块的路径。

安装成功后 /usr/local/nginx 目录下如下

client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp

设置软链接

ln -sv /usr/local/nginx/sbin/nginx /usr/bin/nginx

启动nginx

确保系统的 80 端口没被其他程序占用,运行/usr/local/nginx/sbin/nginx 命令来启动 Nginx

/usr/local/nginx/sbin/nginx
或
Nginx
netstat -ano|grep 80

如果查不到结果后执行,有结果则忽略此步骤(ubuntu下必须用sudo启动,不然只能在前台运行)

sudo /usr/local/nginx/nginx

打开浏览器访问此机器的 IP,如果浏览器出现 Welcome to nginx! 则表示 Nginx 已经安装并运行成功。

nginx命令

 nginx -help
nginx version: nginx/1.24.0
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: /usr/local/nginx//)
  -e filename   : set error log file (default: logs/error.log)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file

配置

The way nginx and its modules work is determined in the configuration file. By default, the configuration file is named nginx.conf and placed in the directory /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx.

nginx 文件结构

...              #全局块

events {         #events块
   ...
}

http      #http块
{
    ...   #http全局块
    server        #server块
    { 
        ...       #server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块
}

1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。
2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。
3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。
4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。
5、location块:配置请求的路由,以及各种页面的处理情况。

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数,默认为512
}
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       4545;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #允许的ip           
        } 
    }
}

上面是nginx的基本配置,需要注意的有以下几点:

1、几个常见配置项:

1.$remote_addr 与 KaTeX parse error: Double subscript at position 7: http_x_̲forwarded_for 用…remote_user :用来记录客户端用户名称;
3. t i m e l o c a l :用来记录访问时间与时区; 4. time_local : 用来记录访问时间与时区; 4. timelocal:用来记录访问时间与时区;4.request : 用来记录请求的url与http协议;
5. s t a t u s :用来记录请求状态;成功是 200 ; 6. status : 用来记录请求状态;成功是200; 6. status:用来记录请求状态;成功是2006.body_bytes_s ent :记录发送给客户端文件主体内容大小;
7. h t t p r e f e r e r :用来记录从那个页面链接访问过来的; 8. http_referer :用来记录从那个页面链接访问过来的; 8. httpreferer:用来记录从那个页面链接访问过来的;8.http_user_agent :记录客户端浏览器的相关信息;
2、惊群现象:一个网路连接到来,多个睡眠的进程被同时叫醒,但只有一个进程能获得链接,这样会影响系统性能。

3、每个指令必须有分号结束。

location 中root、proxy_pass和alias指令

root、proxy_pass和alias都是用来配置Nginx服务器上的URL重写的指令

root指令

root:用于指定文件系统中某个目录作为请求的根目录,Nginx会在该目录下寻找请求的文件。例如:

location /images/ {
    root /var/www;
}

上述配置使得访问/images/目录下的资源时,Nginx会到/var/www/images/目录下查找。
最后请求的路径:root指定的URL/var/www + location上的URL/images/

alias指令

alias:用于将请求映射到另一个目录或文件上(用于将请求的URL路径与文件系统路径进行映射),常用于处理静态资源的请求,这个指令的功能类似于root,只不过可以指定不同的路径。例如:

location /uploads/ {
    alias /var/www/uploads/;
}

上述配置使得访问/uploads/目录下的资源时,Nginx会在/var/www/uploads/目录下查找。注意,使用alias指令时,URI路径会被转换成文件系统路径,例如/uploads/test.jpg会被映射到/var/www/uploads/test.jpg。
最后请求的路径:alias指定的静态资源URL/var/www/uploads/

proxy_pass指令

proxy_pass :用于配置反向代理,将客户端发送的请求转发给指定的后端服务器,并返回后端服务器的响应结果。例如:

location /api/ {
    proxy_pass http://backend_server/;
}

上述配置使得访问/api/目录下的请求会被转发到http://backend_server/服务器上处理。
最后请求的路径:proxy_pass指定的后端服务URLhttp://backend_server/

总结

root适用于指定请求的根目录,
最后请求的路径:root指定的URL + location上的URL

alias则适用于将URL路径映射到文件系统路径,方便访问资源
最后请求的路径:alias指定的静态资源URL

proxy_pass适用于配置反向代理,让Nginx将请求转发给后端服务器。
最后请求的路径:proxy_pass指定的后端服务URL

配置正向代理

代理http没问题,代理https需要先安装一个模块ngx_http_proxy_connect_module
具体安装方法看前面源码安装部分。

server {
    listen                         3128;

    # dns resolver used by forward proxying
    resolver                       8.8.8.8;

    # forward proxy for CONNECT requests
    proxy_connect;
    proxy_connect_allow            443 563;
    proxy_connect_connect_timeout  10s;
    proxy_connect_data_timeout     10s;

    # defined by yourself for non-CONNECT requests
    # Example: reverse proxy for non-CONNECT requests
    location / {
        proxy_pass http://$host;
        proxy_set_header Host $host;
    }
}

另外一种写法

#正向代理
server{
	resolver 114.114.114.114;
	resolver_timeout 30s;
    listen 8888;
	proxy_connect;                          #启用 CONNECT HTTP方法
	proxy_connect_allow            443 80;  #指定代理CONNECT方法可以连接的端口号或范围的列表
	proxy_connect_connect_timeout  20s;     #定义客户端与代理服务器建立连接的超时时间
	proxy_connect_read_timeout     20s;     #定义客户端从代理服务器读取响应的超时时间
	proxy_connect_send_timeout     20s;     #设置客户端将请求传输到代理服务器的超时时间
 
 
	location / {
		 
		proxy_pass $scheme://$http_host$request_uri;
		
	}
	
    
}

配置http文件下载服务器

Nginx也可直接做文件下载服务器使用,在location块设置autoindex相关选项即可。

server {
 
     listen 80 default_server;
     listen [::]:80 default_server;
     server_name  _;
     
     location / {    
         # 下载文件所在目录
         root /usr/share/nginx/html;
         
         # 开启索引功能
         autoindex on;  
         
         # 关闭计算文件确切大小(单位bytes),只显示大概大小(单位kb、mb、gb)
         autoindex_exact_size off; 
         
         #显示本机时间而非 GMT 时间
         autoindex_localtime on;   
                 
         # 对于txt和jpg文件,强制以附件形式下载,不要浏览器直接打开
         if ($request_filename ~* ^.*?\.(txt|jpg|png)$) {
             add_header Content-Disposition 'attachment';
         }
     }
 }

如果存在文件/usr/share/nginx/html/1.exe
http://ip/1.exe就可下载。

提高nginx性能

配置缓存,可提高nginx性能

.如何配置基本缓存设置

开启简单的缓存配置,只需要两个指令:proxy_cache_path和proxy_cache。proxy_cache_path配置缓存的存放地址和其他的一些常用配置,proxy_cache指令是为了启动缓存。

# 在http模块增加以下指令
proxy_cache_path /path/to/cache levels=1:2 keys_zone=mycache:10m max_size=10g inactive=60m use_temp_path=off;
# 在server模块引用
server {
  # ...
  location / {
    proxy_cache mycache;
    proxy_pass http://my_upstream;
  }
}

实际中是这样的

 # 指定缓存cache路径
    proxy_cache_path /var/cache/nginx/ levels=1:2 keys_zone=mycache:10m max_size=10g inactive=60m use_temp_path=off;

    # 以下为下载服务器
    upstream backend {    #负载配置
        server 192.168.1.11:8081;
        server 192.168.1.12:8081;
        server 192.168.1.13:8081;
    }
    server {      #下载服务器配置

     listen 8081 default_server;
     listen [::]:8081 default_server;
     server_name  _;

     location / {
        # 使用缓存
        proxy_cache mycache;
        proxy_pass http://backend;
         }
     }

如果想提高下载速度,可以使用内存盘
参考https://blog.csdn.net/gsl371/article/details/133385203
把这个路径/var/cache/nginx/ 把缓存路径指定到内存盘的路径

    proxy_cache_path /ramdisk/ levels=1:2 keys_zone=mycache:10m max_size=10g inactive=60m use_temp_path=off;

开放防火墙端口

#开启停止firewalld服务

systemctl start firewalld
systemctl stop firewalld
systemctl restart firewalld

#禁用firewalld服务

systemctl mask firewalld  #mask 是注销隐藏了服务

查看已开发端口命令:

firewall-cmd --list-all

1、开放端口

firewall-cmd --zone=public --add-port=80/tcp --permanent

2、重新载入


firewall-cmd --reload

3、查看对应端口

firewall-cmd --zone=public --query-port=80/tcp

4、删除端口

firewall-cmd --zone=public --remove-port=80/tcp --permanent

配置自签名https反向代理

步骤1:生成私钥文件

首先,我们需要生成一个私钥文件,用于服务器与客户端之间的加密通信。可以使用以下命令生成:

openssl genrsa  -out private.key 2048

这将生成一个名为private.key的私钥文件。在当前文件夹下。

步骤2:生成证书签名请求文件

接下来,我们需要生成一个证书签名请求(Certificate Signing Request,CSR)文件,用于向证书颁发机构(Certificate Authority,CA)申请颁发证书。可以使用以下命令生成:

openssl req -new -key private.key -out csr.csr #根据private.key生成一个csr.csr请求文件
#这里会出现以下对话
#Enter pass phrase for domain.key:                          # 之前设置的密码
#-----
#Country Name (2 letter code) [XX]:CN                       # 国家
#State or Province Name (full name) []:Jilin                # 地区或省份
#Locality Name (eg, city) [Default City]:Changchun          # 地区局部名
#Organization Name (eg, company) [Default Company Ltd]:Python # 机构名称
#Organizational Unit Name (eg, section) []:Python           # 组织单位名称
#Common Name (eg, your name or your server's hostname) []:domain.com # 网站域名填nginx配置文件中server_name区域的域名或地址
#Email Address []:123@domain.com                                # 邮箱
#A challenge password []:                                   # 私钥保护密码,可直接回车
#An optional company name []:                               # 一个可选公司名称,可直接回车

这将生成一个名为csr.csr的证书签名请求文件。

步骤3:生成自签名证书

如果不想购买证书,可以自己创建一个自签名证书。可以使用以下命令生成:

openssl x509 -req -days 3650 -in csr.csr -signkey private.key -out certificate.crt #根据请求文件签发crt文件

这将生成一个名为certificate.crt的自签名证书文件。

步骤4:配置Nginx服务器

在Nginx的配置文件中,添加以下内容,进行反向代理和SSL配置:

server {
    listen 80;
    listen 443 ssl ;
    server_name 127.0.0.1;  #或ssl代理服务器域名

    # ssl on;     # 不建议使用! 该指令与listen中ssl参数功能相同.
    ssl_certificate      /etc/nginx/ssl/certificate.crt;
    ssl_certificate_key  /etc/nginx/ssl/private.key;
#    ssl_protocols        TLSv1 TLSv1.1 TLSv1.2;
#    ssl_ciphers          ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
#    ssl_prefer_server_ciphers  on;
#    ssl_session_cache    shared:SSL:10m;
#    ssl_session_timeout  10m;

    # 自动跳转到HTTPS
    if ($server_port = 80) {
        rewrite ^(.*)$ https://$host$1 permanent;
    }

    location / {
               proxy_pass https://www.baidu.com/;  #反向代理的后端服务器
 #             proxy_connect_timeout  30;
 #             proxy_send_timeout   60;
 #             proxy_read_timeout    60;
 #             client_max_body_size  200m;
 #             add_header X-Cache $upstream_cache_status;
 #             proxy_cache_key  $uri$is_args$args;
 #             proxy_http_version 1.1;
 #             proxy_set_header Upgrade $http_upgrade;
 #             proxy_set_header Connection "Upgrade";
 #             proxy_buffer_size 128k;
 #             proxy_buffers 32 32k;
 #             proxy_busy_buffers_size 128k;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 #             proxy_set_header REMOTE-HOST $remote_addr;
}
}

在配置完成后,重启Nginx服务器使配置生效。这样,Nginx就会将用户的请求从80端口(非加密)转发至443端口(加密),实现SSL加密传输。

其他实例


server {
    listen 80;
    listen 443 ssl http2;
    server_name 127.0.0.1;
    
    # ssl on;     # 不建议使用! 该指令与listen中ssl参数功能相同.
    ssl_certificate      /etc/nginx/ssl/server.crt;
    ssl_certificate_key  /etc/nginx/ssl/server.key;
    ssl_protocols        TLSv1 TLSv1.1 TLSv1.2
    ssl_ciphers          ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers  on;
    ssl_session_cache    shared:SSL:10m;
    ssl_session_timeout  10m;
 
    # 自动跳转到HTTPS
    if ($server_port = 80) {
        rewrite ^(.*)$ https://$host$1 permanent;
    }
 
    location /code01/ {
              proxy_pass https://后端服务:8089/;
              proxy_connect_timeout  30;
              proxy_send_timeout   60;
              proxy_read_timeout    60;
              client_max_body_size  200m;
              add_header X-Cache $upstream_cache_status;
              proxy_cache_key  $uri$is_args$args;
              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "Upgrade";
              proxy_buffer_size 128k;
              proxy_buffers 32 32k;
              proxy_busy_buffers_size 128k;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header REMOTE-HOST $remote_addr;
}

location /code02/ {
              proxy_pass https://后端服务:8090/;
              proxy_connect_timeout  30;
              proxy_send_timeout   60;
              proxy_read_timeout    60;
              client_max_body_size  200m;
              add_header X-Cache $upstream_cache_status;
              proxy_cache_key  $uri$is_args$args;
              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "Upgrade";
              proxy_buffer_size 128k;
              proxy_buffers 32 32k;
              proxy_busy_buffers_size 128k;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header REMOTE-HOST $remote_addr;
}

location /code03/ {
              proxy_pass https://后端服务:8091/;
              proxy_connect_timeout  30;
              proxy_send_timeout   60;
              proxy_read_timeout    60;
              client_max_body_size  200m;
              add_header X-Cache $upstream_cache_status;
              proxy_cache_key  $uri$is_args$args;
              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "Upgrade";
              proxy_buffer_size 128k;
              proxy_buffers 32 32k;
              proxy_busy_buffers_size 128k;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header REMOTE-HOST $remote_addr;
}
}

配置HTTP 负载均衡

通过多个应用实例的负载均衡,一般是指用来优化资源使用率,最大化的吞吐,减少延迟,并具有容容错能力的配置。nginx和nginx plus可以被用来部署在多种应用场景,来作为一个有效的http负载均衡。

代理http流量到一组服务器

第一步,首先要定义一个上游服务器组标识,这个标识位于配置文件的http块中。
这个组中的服务器被配置成使用在在配置文件server块中定义的指向,不能和虚拟服务器混为一谈。

http {
    upstream backend {
        server backend1.example.com weight=5;
        server backend2.example.com;
        server 192.0.0.1 backup;
    }
}

传递请求到这这个服务器组,是通过一个proxy_pass指向来实现的。下面例子,nginx上的虚拟服务器传递所有请求到这个前面定义的backend upstream服务器组。

server {
    location / {
        proxy_pass http://backend;
    }
}

下面是上面片段的组合,由于没有指定负载均衡算法,将使用默认轮训算法。round robin。

http {
    upstream backend {
        server backend1.example.com;
        server backend2.example.com;
        server 192.0.0.1 backup;
    }
    
    server {
        location / {
            proxy_pass http://backend;
        }
    }
}

选择一种负载均衡算法

nginx支持四种算法,nginx plus支持六种算法。
1、Round Robin
默认算法,根据服务器权重来执行。

upstream backend {
   # no load balancing method is specified for Round Robin
   server backend1.example.com;
   server backend2.example.com;
}

2、Least Connections
服务器的最少活动连接将被考虑。

upstream backend {
    least_conn;
    server backend1.example.com;
    server backend2.example.com;
}

3、IP Hash
通过客户端IP地址的hash值来确定服务器,这种方法还保证同一客户ip,下次发送到同一服务器。

upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
}

临时剔除的服务器可以加down标记

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com down;
}

4、Generic Hash – The server to which a request is sent is determined from a user‑defined key which can be a text string, variable, or a combination. For example, the key may be a paired source IP address and port, or a URI as in this example:

upstream backend {
    hash $request_uri consistent;
    server backend1.example.com;
    server backend2.example.com;
}

服务器权重

默认权重是1

upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com;
    server 192.0.0.1 backup;
}

标记为backup的不接受请求,除非其它两个故障。6个请求5个给backend1,1个给backend2.

服务器慢进入

服务器慢进入特性,防止刚恢复进入组的服务器,接受大量请求,造成超时,被标记为故障而又退出。

upstream backend {
    server backend1.example.com slow_start=30s;
    server backend2.example.com;
    server 192.0.0.1 backup;
}

会话保持

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
CentOS 7上安装Nginx有几种方法可以选择。方法一是使用rpm命令进行安装,具体命令为:rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm。在执行这个命令之前,需要先安装epel包,可以使用sudo yum install yum-utils命令进行安装安装完成后,可以执行yum install epel-release命令查看已安装的epel包。接下来,执行rpm命令进行Nginx安装安装完成后,可以通过whereis nginx命令查找Nginx文件,一般安装在/usr/local/nginx目录下。然后进入该目录,使用./configure命令进行配置,紧接着使用make命令编译,最后使用make install命令确认安装是否成功。最后,启动Nginx服务即可。方法二是从官网下载Nginx,使用XShell和Xftp将压缩包上传到Linux虚拟机中,然后在Linux虚拟机中解压文件,配置Nginx,启动Nginx,并进行一些拓展操作,如修改端口和使用常用命令。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【LinuxCentOS7操作系统安装nginx实战(多种方法,超详细)](https://blog.csdn.net/wisdom_futrue/article/details/129334966)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Linux操作系统CentOS7安装Nginx[详细版]](https://blog.csdn.net/Wei_Naijia/article/details/124228897)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值