nginx合集

一、nginx安装的三种方式。

    1.yum安装

[root@recall-1 ~]#yum -y install nginx                 #yum安装nginx
[root@recall-1 ~]# rpm -qc nginx                       #查看配置文件位置
/etc/logrotate.d/nginx
/etc/nginx/fastcgi.conf
/etc/nginx/fastcgi.conf.default
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/mime.types.default
/etc/nginx/nginx.conf                                        
/etc/nginx/nginx.conf.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params
/etc/nginx/uwsgi_params.default
/etc/nginx/win-utf
    

    2.rpm安装

[root@recall-1 ~]# rpm -ihv nginx-1.16.1-1.el7.ngx.x86_64.rpm
[root@recall-1 ~]# rpm -qc nginx                       #查看配置文件位置
/etc/logrotate.d/nginx
/etc/nginx/fastcgi.conf
/etc/nginx/fastcgi.conf.default
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/mime.types.default
/etc/nginx/nginx.conf                                        
/etc/nginx/nginx.conf.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params
/etc/nginx/uwsgi_params.default
/etc/nginx/win-utf
 

    3.源码安装(推荐)(./configure --help可以查看所有模块)

[root@recall-1 ~]# ls
anaconda-ks.cfg  default  nginx-1.20.1.tar.gz
[root@recall-1 ~]# tar -xf nginx-1.20.1.tar.gz
[root@recall-1 ~]# cd nginx-1.20.1
[root@recall-1 ~]# yum -y install pcre-devel openssl-devel
[root@recall-1 nginx-1.20.1]# ./configure --prefix=/usr/local/nginx     #指定位置安装
[root@recall-1 nginx-1.20.1]# make && make install
 

4.为以及安装的nginx添加模块(编译安装模式,源码包用同一个版本的)

[root@recall-1 ~]# nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
configure arguments: --prefix=/usr/local/nginx
[root@recall-1 ~]# ls
anaconda-ks.cfg  default  nginx-1.20.1.tar.gz
[root@recall-1 ~]# tar -xf nginx-1.20.1.tar.gz
[root@recall-1 ~]# cd nginx-1.20.1
[root@recall-1 nginx-1.20.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@recall-1 nginx-1.20.1]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module
[root@recall-1 nginx-1.20.1]# make                                                              #别make install  要不然直接GG
[root@recall-1 nginx-1.20.1]# mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak    #备份老的二进制文件
[root@recall-1 nginx-1.20.1]# cp objs/nginx /usr/local/nginx/sbin/nginx                         #拷贝新的二进制文件
[root@recall-1 nginx-1.20.1]# nginx -V
nginx version: nginx/1.20.1
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=/usr/local/nginx --with-http_ssl_module
 
 
 
 

二、nginx的配置文件详解

1.优化后的nginx配置文件

 
 
user nginx;                
#优化1.工作进程数量 auto为自动       
worker_processes auto;             
 
 
#pid /usr/local/nginx/logs/nginx.pid;
 
 
#优化2.nginx最大文件打开数
worker_rlimit_nofile    65536;     
 
 
events {      
      #优化3.nginx事件处理epoll模型       
      use epoll;                   
  #优化4.进程允许客户端最大链接数     
      worker_connections 65535;    
}
 
 
http {
 
 
# Basic Settings  
charset UTF-8;
 
 
#优化5.开启高速传输配置  
sendfile on;   #开启高速传输                 
tcp_nopush on;  #数据不会马上发出去,而是等到数据包最大时,一次性的传输出去,这样有助于解决网络堵塞。
tcp_nodelay on;   #只要有数据包产生,不管大小多少,就尽快传输
 
 
types_hash_max_size 2048;
#        
    #优化6.链接超时时间############
# 长连接超时配置
keepalive_timeout  65;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 300s;
 
 
#优化7.隐藏版本号##############  
server_tokens off;            
 
 
#优化8.限制文件上传大小     
client_max_body_size 8m;      
 
 
#include /etc/nginx/mime.types;
default_type application/octet-stream;
 
 
# SSL Settings                   #优化9.开启ssl证书协议   
 
 
ssl_certificate /usr/local/nginx/conf/server.pem;
ssl_certificate_key /usr/local/nginx/conf/server.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
 
 
# Logging Settings#优化10.前端有防火墙才会用这个日志格式
        log_format  main   - []       ;                     
access_log /usr/local/nginx/logs/access.log;
error_log /usr/local/nginx/logs/error.log;
 
 
 
 
        #ip limit        #优化11.nginx访问限速
        #限制用户连接数来预防DOS攻击
        limit_conn_zone $binary_remote_addr zone=perip:10m;
        limit_conn_zone $server_name zone=perserver:10m;
        #限制同一客户端ip最大并发连接数
        limit_conn perip 200;
        #限制同一server最大并发连接数
limit_conn perserver 200;
#限制下载速度,根据自身服务器带宽配置
limit_rate 3000k;
 
 
 
 
        #响应头
        add_header X-Cache $upstream_cache_status;
#        add_header X-Frame-Options SAMEORIGIN;
        add_header X-Content-Type-Options nosniff;
    
# Gzip Settings      #优化12.配置网页压缩gzip    
gzip on;
gzip_disable "msie6";
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 6;
        gzip_buffers 16 8k;
        gzip_http_version 1.1;
        gzip_types image/png text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif;
 
 
# Virtual Host Configs   #优化13.设置vhost配置路径     
include /usr/local/nginx/conf/vhost/*.conf;      #  /usr/local/nginx/conf/vhost文件夹需要手动创建
}
 

2.server虚拟主机介绍

server {
    listen       80;                       #虚拟主机使用的端口
    server_name  localhost;                #虚拟主机使用的域名
    location / {                                                
        root   html;                       #虚拟主机web文件家目录
        index  index.html index.htm;       #index文件
}
}
 
以上为一个简单的server虚拟主机
 
1.基于ip的虚拟主机
server {
        listen 10.0.0.9:80;
        location / {
                root /code/addr1;
                index index.html;
        }
}
2.基于端口的虚拟主机
server {
    listen 80;
    server_name localhost;
    location / {
    root /code/tuixiangzi;
    index index.html;
    }
}
3.基于域名的虚拟主机
server {
    listen 80;
    server_name www.tuixiangzi.com;
    location / {
        root /code/tuixiangzi;
        index index.html;
    }
}
 
 

3.nginx location规则编写

 
1、location的五种匹配策略
    
        =    完全匹配                       
        
        ^~    匹配以什么字符开头  
        
        ~    正则匹配(区分大小写)
        
        ~*  正则匹配(不区分大小写)
        
        /    匹配所有内容
        
        优先级:
        
=            1
^~          2
~            3
~*            3
/            4
   
案例:
        [root@web02 conf.d]# cat game.conf
        server {
            server_name game.test.com;
            listen 80;
 
 
            location / {
                root /usr/share/nginx/html5-mario;
                index index.html;
            }
 
 
                location ~* \.(png|gif|jpg|jpeg|mp4|mp3)$ {
                        root /usr/share/nginx;
                }
        }
 
 
优先级验证:
[root@web01 ~]# vim /etc/nginx/conf.d/youxianji.conf
server {
    listen 80;
    server_name linux.test.com;
    location / {
        default_type text/html;
        return 200 "location /";
    }
    location =/ {
        default_type text/html;
        return 200 "location =/";
    }
    location ~ / {
        default_type text/html;
        return 200 "location ~/";
    }
    # location ^~ / {
    #   default_type text/html;
    #   return 200 "location ^~";
    # }
}
 
 
location应用场景:
# 通用匹配,任何请求都会匹配到
location / {
    ...
}
# 严格区分大小写,匹配以.php结尾的都走这个location    
location ~ \.php$ {
    ...
}
# 严格区分大小写,匹配以.jsp结尾的都走这个location
location ~ \.jsp$ {
    ...
}
# 不区分大小写匹配,只要用户访问.jpg,gif,png,js,css 都走这条location
location ~* .*\.(jpg|gif|png|js|css)$ {
    ...
}
http://linux.test.com/1.PHP
http://linux.test.com/1.JPG
http://linux.test.com/1.jsp
http://linux.test.com/1.Gif
http://linux.test.com/1.PnG
http://linux.test.com/1.JsP
 
 

 4.rewrite地址重写

 

什么是rewrite
url地址重写,以及重定向,就是把传入web的请求重定向到其他url的过程


rewrite使用场景
1.地址跳转:用户访问www.linux.com这个URL是,将其定向至一个新的域名www.baidu.com
2.协议跳转:用户通过http协议请求网站时,将其重新跳转至https协议方式
3.伪静态:将动态页面显示为静态页面方式的一种技术,便于搜索引擎的录入,同时建上动态URL地址对外暴露过多的参数,提升更高的安全性。
4.搜素引擎:SEO优化依赖于url路径,好记的url便于搜索引擎录入

nginx配置
rewrite [匹配内容] [从定向到的内容] [重定向规则];

 

rewrite标记

last 本条规则匹配完成后,停止匹配,不在匹配后面的规则
break 本条规则匹配完成后,停止匹配不在匹配后面的规则
redirect 返回302临时重定向,地址栏会显示跳转后的地址
permanent 返回301永久重定向,地址栏会显示跳转后的地址


区别详解:
last 是在nginx内部按照重定向的规则重新访问一遍
break 是在nginx内部按照重定向的规则去对应的目录访问

redirect 临时重定向浏览器不记录缓存
permanent 永久重定向浏览器是会记录缓存,再一次访问将不再走nginx服务端,直接在浏览器跳转

 
 
 
 
 
 
 
 

三、nginx的模块安装以及使用

1.目录索引模块

模块:ngx_http_autoindex_module     #添加模块步骤上面有些这里就不在写了
 
使用语法:
    autoindex on;                #开启目录索引
    autoindex_exact_size off;    #文件大小格式化(四舍五入)
    autoindex_localtime on;      #显示本机时间
 
添加的位置:
http, server, location均可
 

2.nginx访问控制模块

模块:ngx_http_access_module
 
使用语法:
        允许访问:
                allow ip | all;
        拒绝访问:
                deny address | all ;
 
添加的位置:http, server, location, limit_except
#如果配置允许,则也要配置拒绝;配置拒绝可以单独配置
 
 
例题:
拒绝指定ip其他全部允许
[root@web01 ~]# vim /etc/nginx/conf.d/www.autoindex.com.conf
server {
    listen 80;
    server_name www.autoindex.com;
    charset utf8;
    location / {
        root /code/autoindex;
        index index.html;
    }
    location /download {
        root /code/autoindex;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        allow 10.0.0.1;
        #如果使用all,一定放在最后面
        deny all;
    }
}
 
 
例题:只允许指定ip,其他全部拒绝。
[root@web01 ~]# vim /etc/nginx/conf.d/www.autoindex.com.conf
server {
    listen 80;
    server_name www.autoindex.com;
    charset utf8;
    location / {
        root /code/autoindex;
        index index.html;
    }
    location /download {
        root /code/autoindex;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        allow 10.0.0.1;
        #如果使用all,一定放在最后面
        deny all;
    }
}
 
例题:只允许10.0.0.1访问,拒绝改网段其他ip
[root@web01 ~]# vim /etc/nginx/conf.d/www.autoindex.com.conf
server {
    listen 80;
    server_name www.autoindex.com;
    charset utf8;
    location / {
        root /code/autoindex;
        index index.html;
    }
    location /download {
        root /code/autoindex;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        allow 10.0.0.1;
        #如果使用all,一定放在最后面
        deny 10.0.0.0/24;
    }
}
 

3.访问认证模块

 
需要用到的模块工具
模块:ngx_http_auth_basic_module
工具: yum -y install htpasswd
 
创建密码文件:
[root@web01 ~]# htpasswd -c /etc/nginx/auth_basic lhd
New password:
Re-type new password:
Adding password for user lhd
#添加一个登录用户
[root@web01 ~]# htpasswd /etc/nginx/auth_basic egon
New password:
Re-type new password:
Adding password for user egon
 
配置访问登录
使用关键字:
auth_basic on;
auth_basic_user_file /etc/nginx/auth_basic;
 
添加位置:http, server, location
 

 

4.更多模块配置请前往:

 
 
 

四、常用服务。

1.反向代理(反向代理、负载均衡、七层负载均衡都是这货)

例子:
upstream  server {         #server为集群名字可以随便写
    server 192.168.159.10:80;                #不加端口默认为80
    server 192.168.159.20:80;
}
 
server {    
    ……
    location / {
        proxy_pass http://server;
}
}
分配策略:
轮询(默认)每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
weight(轮询几率): 指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的
情况。
ip_hash:用户第一次访问的是那一台服务器,接下来访问的都是那一台服务器。
upstream backserver {
    ip_hash;
    server 192.168.0.14:88;
    server 192.168.0.15:80;
}
fari(第三方): 按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream backserver {
    server server1;
    server server2;
    fair;
}
url_hash(第三方): 按访问url的hash结果来分配请求,使每个url定向到同一个(对应的)后端服务器,后端服务器为缓存时比较有效。
upstream backserver {
    server squid1:3128;
    server squid2:3128;
    hash $request_uri;
    hash_method crc32;
}
 
附加:
proxy_pass http://backserver/;
upstream backserver{
    ip_hash;
    server 127.0.0.1:9090 down; (down 表示单前的server暂时不参与负载)
    server 127.0.0.1:8080 weight=2; (weight 默认为1.weight越大,负载的权重就越大)
    server 127.0.0.1:6060;
    server 127.0.0.1:7070 backup; (其它所有的非backup机器down或者忙的时候,请求backup机器)
}
 

2.四层负载均衡

需要安装的模块:--with-srearm
安装后配置文件修改:
把配置文件里面整个http删了,换成:
stream {
}
案例1要求使用192.168.15.6的1234端口链接192.168.15.5的22端口
            [root@lb02 stream.conf]# cat ssh.conf
            upstream ssh {
                server 172.16.1.5:22;
            }
            server {
                listen 1234;
                proxy_pass ssh;
            }
案例2:要求使用192.168.15.6的33060端口代理192.168.15.51的3306端口
 
            [root@lb02 stream.conf]# cat mysql.conf
            upstream mysql {
                server 172.16.1.51:3306;
            }
 
 
            server {
                listen 33060;
                proxy_pass mysql;
            }
 

3.https加密(单机)。

模块:--with-http_ssl_module
 
关于实验用证书获取的两种方式:
1.阿里云免费申请。(有小绿锁)
2.自己生成。(没有小绿锁)
生成证书:
openssl genrsa -out cert.key
openssl req -new -x509 -key cert.key -out cert.pem
 
修改配置文件(添加)
server {
    listen       443 ssl;
    ……
            ssl_certificate      /etc/local/nginx/conf/cert.pem;    
        ssl_certificate_key  /etc/local/nginx/conf/cert.key;
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
 
 
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;    
}
 
测试修改是否正确
[root@web02 conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
 
重启nginx
[root@web02 conf]# /usr/local/nginx/sbin/nginx -s reload
 

4.全站https。

以下是配置没什么好说的了
 
upstream backserver {
        server 172.16.1.7:80;
        server 172.16.1.8:80;
        server 172.16.1.9:80;
}
 
 
server {
    listen 80;
    server_name www.mycentos.top;
    return 301 https://www.mycentos.top;
}
server {
    listen 443 ssl;
    server_name www.mycentos.top;
    ssl_certificate      /usr/local/nginx/conf/server.pem;
    ssl_certificate_key  /usr/local/nginx/conf/server.key;
    ssl_prefer_server_ciphers  on;
    location / {
        proxy_pass http://backserver;
}
}
 
 

五、nginx高可用keepalived

 
keepalived高可用(私网)
        部署在整个集群中的一个高可用软件,作用是创建一个VIP(虚拟IP),在整个集群中有且只有一个机器上生成VIP,当这台机器出现问题时,keepalived将自动将VIP切换至其他的某一台服务器上。
 

1.部署keepalived:

1.server1、server2安装keepalived
yum install keepalived -y
 
 
2.修改配置文件。
吧原来的清空了,然后在吧这个复制过去修改
server1:
 
 
#全局配置
global_defs {
    #身份识别(全局唯一)
    router_id lb01
}
# 配置VRRP协议
vrrp_instance VI_1 {
    # 状态,MASTER和BACKUP(这里仅仅是一个标记,正真确认VIP的是权重)
    state BACKUP
    nopreempt
    # 绑定网卡
    interface eth0
    # 虚拟路由标示,可以理解为分组
    virtual_router_id 50
    # 优先级(数字越大,权重越大)
    priority 100
    # 监测心跳间隔时间
    advert_int 1
    # 配置认证
    authentication {
        # 认证类型
        auth_type PASS
        # 认证的密码
        auth_pass 1111
    }
    # 设置VIP
    virtual_ipaddress {
        # 虚拟的VIP地址
        192.168.159.33
    }
 
}
server2:
 
#全局配置
global_defs {
    #身份识别(全局唯一)
    router_id lb02
}
# 配置VRRP协议
vrrp_instance VI_1 {
    # 状态,MASTER和BACKUP(这里仅仅是一个标记,正真确认VIP的是权重)
    state BACKUP
    nopreempt
    # 绑定网卡
    interface eth0
    # 虚拟路由标示,可以理解为分组
    virtual_router_id 50
    # 优先级(数字越大,权重越大)
    priority 90
    # 监测心跳间隔时间
    advert_int 1
    # 配置认证
    authentication {
        # 认证类型
        auth_type PASS
        # 认证的密码
        auth_pass 1111
    }
    # 设置VIP
    virtual_ipaddress {
        # 虚拟的VIP地址
        192.168.159.33
    }
}
注意:vip地址必须和绑定网卡地址一个网段
 
3.重启测试
server1、server2:
systemctl restart keepalived
 
用ip a查看ip地址。
 
 

2.抢占士和非抢占式

        state BACKUP    (所有的机器全部设置成BACKUP)
        #开启非抢占式    
        nopreempt
 
解决了那些问题:
        当master宕机切换到backup的时候会短暂一小段时间无法访问,当master恢复服务时候切换回来又宕机一小段时间,如果全部设置问backup那么就没有master切换过去除非宕机要不然不会切换回来了
 

3.高可用时如果出现脑裂问题时怎么解决

 
在配置文件添加
1、通过一个脚本判断
        
            #每5秒执行一次脚本,脚本执行内容不能超过5秒,否则会中断再次重新执行脚本
            vrrp_script check_web {
                # 指定脚本路径
                script "/etc/keepalived/check.sh"
                # 5秒钟执行一次
                interval 5
            }
                
            #调用计划的脚本
            track_script {
                check_web
            }
 
例:
#全局配置
global_defs {
    #身份识别(全局唯一)
    router_id lb01
}
 
 
#每5秒执行一次脚本,脚本执行内容不能超过5秒,否则会中断再次重新执行脚本
vrrp_script check_web {
    # 指定脚本路径
    script "/etc/keepalived/check.sh"
    # 5秒钟执行一次
    interval 5
}
 
 
# 配置VRRP协议
vrrp_instance VI_1 {
    # 状态,MASTER和BACKUP(这里仅仅是一个标记,正真确认VIP的是权重)
    state BACKUP
    nopreempt
    # 绑定网卡
    interface eth0
    # 虚拟路由标示,可以理解为分组
    virtual_router_id 50
    # 优先级(数字越大,权重越大)
    priority 100
    # 监测心跳间隔时间
    advert_int 1
    # 配置认证
    authentication {
        # 认证类型
        auth_type PASS
        # 认证的密码
        auth_pass 1111
    }
    # 设置VIP
    virtual_ipaddress {
        # 虚拟的VIP地址
        192.168.159.33
    }
 
 
    #调用计划的脚本
    track_script {
        check_web
    }
}
 
脚本:
[root@lb01 ~]# cat /etc/keepalived/check.sh
#!/bin/bash
#1.判断端口
#2.通过进程的方式
 
 
ps -aux | grep [n]ginx
if [ $? -ne 0 ] ; then
    /usr/local/nginx/sbin/nginx
    sleep 3;
    ps -aux | grep [n]ginx
    if [ $? -ne 0 ] ; then
    systemctl stop keepalived
    fi
 
 
fi
 
 
 
 
 

 ······待完善········

posted @ 2021-11-01 21:30  念长卿  阅读(81)  评论(0)    收藏  举报