Centos7.9 安装 Nginx与配置

Centos7.9 安装 Nginx

1.下载与安装

官方网址:http://nginx.org/en/download.html nginx-1.22.1.tar.gz,上传到Linux系统中

在这里插入图片描述

  1. 安装环境依赖

    # 安装gcc环境依赖
    yum install -y gcc-c++
    # 安装PCRE库,用于解析正则表达式
    yum install -y pcre pcre-devel
    # zlib压缩和解压缩依赖
    yum install -y zlib zlib-devel
    # SSL 安全的加密的套接字协议层,用于HTTP安全传输,也就是https
    yum install -y openssl openssl-devel
    
  2. 解压 nginx-1.22.1.tar.gz,解压后得到的是源码,源码需要编译后才能安装

tar -zxvf nginx-1.22.1.tar.gz
  1. 编译之前,先创建nginx临时目录,如果不创建,在启动nginx的过程中会报错

    mkdir /var/temp/nginx -p
    
  2. 在nginx目录,输入如下命令进行配置,目的是为了创建makefile文件

    ./configure \
    --prefix=/usr/local/nginx \
    --pid-path=/var/run/nginx/nginx.pid \
    --lock-path=/var/lock/nginx.lock \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --with-http_gzip_static_module \
    --http-client-body-temp-path=/var/temp/nginx/client \
    --http-proxy-temp-path=/var/temp/nginx/proxy \
    --http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
    --http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
    --http-scgi-temp-path=/var/temp/nginx/scgi
    

配置解释

命令解释
–-prefix指定nginx安装目录
–-pid-path指向nginx的pid
-–lock-path锁定安装文件,防止被恶意篡改或误操作
-–error-log错误日志
-–http-log-pathhttp日志
-–with-http_gzip_static_module启用gzip模块,在线实时压缩输出数据流
-–http-client-body-temp-path设定客户端请求的临时目录
-–http-proxy-temp-path设定http代理临时目录
-–http-fastcgi-temp-path设定fastcgi临时目录
-–http-uwsgi-temp-path设定uwsgi临时目录
-–http-scgi-temp-path设定scgi临时目录
  1. make 编译安装

    make
    make install
    # 查找nginx的安装目录
    [root@bogon nginx-1.22.1]# whereis nginx
    nginx: /usr/local/nginx
    
  2. 进入sbin目录启动nginx

    cd /usr/local/nginx/sbin
    # 启动
    ./nginx
    # 停止
    ./nginx -s stop
    ./nginx -s quit
    ./nginx -s reload
    # 检查配置文件是否是OK的
    ./nginx -t
    
  3. 打开浏览器进行访问,默认端口是:80

2.进程模型

[root@bogon conf]# ps -ef|grep nginx
root     16454     1  0 03:52 ?        00:00:00 nginx: master process ./nginx
nobody   16455 16454  0 03:52 ?        00:00:00 nginx: worker process
root     16462  1434  0 04:00 pts/0    00:00:00 grep --color=auto nginx

nginx是由master和worker进程构成,master进程只有一个,worker进程默认只有一个,可以通过配置文件进行配置,master发送指令给worker去执行。

3.配置文件

# 1.设置worker进程的用户,指的linux中的用户,会涉及到nginx操作目录或文件的一些权限,默认为 nobody
#user  nobody;
# 2.worker进程工作数设置,一般来说CPU有几个,就设置几个,或者设置为N-1也行
worker_processes  1;
# 3.nginx日志级别 debug|info|notice|warn|error|crit|alert|emerg,错误级别从左到右越来越大
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
# 4.设置nginx进程 pid
#pid        logs/nginx.pid;

# 5.设置工作模式
events {
    # 默认使用epoll
	use epoll;
	# 每个worker允许连接的客户端最大连接数
    worker_connections  1024;
}


http {
    # 6.include引入外部配置,提高可读性,避免单个配置文件过大
    include       mime.types;
    # 默认文件类型
    default_type  application/octet-stream;
    # 设定日志格式
    #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  logs/access.log  main;

    # 7.sendfile 使用高效文件传输,提升传输性能。
    # 启用后才能使用tcp_nopush,是指当数据表累积一定大小后才发送,提高了效率
    sendfile        on;
    #tcp_nopush     on;

    # 8.设置客户端与服务端请求的超时时间,保证客户端多次请求的时候不会重复建立新的连接,节约资源损耗
    #keepalive_timeout  0;
    keepalive_timeout  65;

    # 9.gzip启用压缩,html/js/css压缩后传输会更快
    #gzip  on;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
    }
}

日志格式化参数

参数名参数意义
$remote_addr客户端ip
$remote_user远程客户端用户名,一般为:’-’
$time_local时间和时区
$request请求的url以及method
$status响应状态码
$body_bytes_send响应客户端内容字节数
$http_referer记录用户从哪个链接跳转过来的
$http_user_agent用户所使用的代理,一般来时都是浏览器
$http_x_forwarded_for通过代理服务器来记录客户端的ip

3.1 root与alias的区别

服务器资源路径:/home/wms/images/face.png

  • root 路径完全匹配访问

    location /wms {
        root /home
    }
    

    访问请求路径: url:port/wms/files/images/face.png

  • alias 可以为你的路径做一个别名,对用户透明

    location /hello {
        alias /home/wms
    }
    

    访问请求路径: url:port/hello/images/face.png ,相当于给 /home/wms 自定义一个别名 /hello

3.2 gzip文件压缩

#开启 gzip压缩功能,目的: 提高传输效率,节约带宽
gzip on;
#限制最小压缩,小于1字 节文件不会压缩
gzip min length 1:
#定义压缩的级别 (压缩比,文件越大,压缩越多,但是cpu使用会越多)
gzip_comp level 3;
#定义压缩文件的类型
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/json;

3.3 location匹配规则

空格 :默认匹配,普通匹配

location / {
    root /home;
}

= :精确匹配

location = /wms/images/face1.png {
	root /home;
}

~* :匹配正则表达式,不区分大小写

# 符合图片的显示
location ~* \.(GIF|jpg|png|jpeg) {
	root /home;
}

~ :匹配正则表达式,区分大小写

#GIF必须大写才能匹配到
location ~ \.(GIF|jpg|png|jpeg) {
	root /home;
}

^~ :以某个字符路径开头,^非的意思,就是不适用正则表达式

location ^~ /imooc/img {
	root /home;
}

3.4 nginx跨域配置

server {
        listen       80;
        server_name  localhost;
        
        #允许跨域请求的域,*代表所有
        add_header 'Access-Control-Allow-Origin' *;
        #允许带上cookie请求
        add_header 'Access-Control-Allow-Credentials' 'true';
        #允许请求的方法,比如 GET/POST/PUT/DELETE
        add_header 'Access-Control-Allow-Methods' *;
        #允许请求的header
        add_header 'Access-Control-Allow-Headers' *;
        
        location / {
            root   html;
            index  index.html index.htm;
        }
}

3.5 静态资源防盗链

server {
        listen       80;
        server_name  localhost;
        
        #对源站点验证
        valid_referers *.imooc.com;
        #非法引入会进入下方判断
        if ($invalid_referer) {
        	return 404;
        }
        
        location / {
            root   html;
            index  index.html index.htm;
        }
}

3.6 负载均衡

3.6.1 轮询(默认)
upstream tomcats {
    server 192.168.1.110:8080;
    server 192.168.1.111:8080;
    server 192.168.1.112:8080;
}

server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://tomcats;
    }
}
3.6.2 权重
upstream tomcats {
    server 192.168.1.110:8080 weight=2;
    server 192.168.1.120:8080 weight=3;
    server 192.168.1.130:8080 weight=5;
    
    # server 192.168.1.140:8080 max_conns=2;
    # server 192.168.1.140:8080 weight=6 slow_start=60s;
    # server 192.168.1.140:8080 down;
    # server 192.168.1.140:8080 backup;
    # server 192.168.1.140:8080 max_fails=2 fail_timeout=15s;
}

server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://tomcats;
    }
}

如果有10个请求过来,2个回到 110,3个回到 120,5个会到 130

max_conns:限制每台server的连接数,用于保护避免过载,可起到限流作用。

slow_start:使服务器慢慢的加入到集群中,该参数不能在 hash 和 random load balancing 中使用,如果在 upstream 中只有一台 server,则该参数失效。

down:用于标记服务节点不可用。

backup:表示当前服务器节点是备用机,只有在其他的服务器都宕机以后,自己才会加入到集群中,被用户访问到,不能在 hash 和 random load balancing 中使用。

max_fails:表示失败几次,则标记server已宕机,剔出上游服务。

fail_timeout:表示失败的重试时间。

在15秒内请求某一server失败达到2次后,则认为该server已经挂了或者宕机了,随后再过15秒,这15秒内不会有新的请求到达刚刚挂掉的节点上,而是会在正常运作的server上,15秒后会再有新请求尝试连接挂掉的server,如果还是失败,重复上一过程,直到恢复。

3.6.3 keepalive 提高吞吐量
upstream tomcats {
    server 192.168.1.110:8080;
    server 192.168.1.120:8080;
    server 192.168.1.130:8080;
    keepalive 32;
}
server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://tomcats;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

keepalived : 设置长连接处理的数量

proxy_http_version :设置长连接http版本为1.1

proxy_set_header :清除connection header 信息

3.6.4 ip_hash、url_hash、least_conn

ip_hash 保证用户请求到上游服务中固定的服务器,前提是用户ip没有发生更改,需要注意的是 ip_hash 不能把后台服务器直接移除,只能标记 down

url_hash 根据每次请求的url地址,hash后访问到固定的服务器节点。

least_conn 请求当前处理连接数最少的服务器。

upstream tomcats {
	# url hash
	hash $request_uri;
	# 最少连接数
	# least_conn
	server 192.168.1.110:8080;
    server 192.168.1.120:8080;
    server 192.168.1.130:8080;
}
server {
	listen 80;
	server_name localhost;
    location / {
    	proxy_pass http://tomcats;
    }
}

3.7 缓存

3.7.1 浏览器缓存

加速用户访问,提升单个用户(浏览器访问者)体验,缓存在浏览器本地。

location /apps {
    alias /home;
    # expires 10s; # 10秒后过期
    # expires @22h30m; # 晚上22点30分过期
    # expires -1h; # 缓存提前过期(一个小时前缓存已经失效了)
    # expires epoch; # 不适用缓存,1970年缓存已经失效了
    # expires off; # 默认,nginx不做缓存处理,浏览器端自己做缓存的处理
    # 设置缓存的最大时间
    expires max;
}
3.7.2 Nginx缓存

缓存在nginx端,提升所有访问到nginx这一端的用户,提升访问上游(upstream)服务器的速度,用户访问仍然会产生请求流量。

# proxy_cache_path 设置缓存目录
# keys_zone 设置共享内存以及占用空间大小
# max_size 设置缓存大小
# inactive 超过此时间则被清理
# use_temp_path 临时目录,使用后会影响nginx性能
proxy_cache_path /usr/local/nginx/upstream_cache keys_zone=mycache:5m max_size=1g inactive=1m use_temp_path=off;

location / {
    proxy_pass http://tomcats;
    # 启用缓存,和keys_zone一致
    proxy_cache mycache;
    # 针对200和304状态码缓存时间为8小时
    proxy_cache_valid 200 304 8h;
}

3.8 Https 访问配置

4.日志切割

现有的日志都会存在 access.log 文件中,但是随着时间的推移,这个文件的内容会越来越多,体积会越来越大,不便于运维人员查看,所以我们可以通过把文件切割为多份不同的小文件作为日志,切割规则可以以 为单位。

  1. 创建一个shell可执行文件: cut_nginx_log.sh ,内容为

    #!/bin/bash
    LOG_PATH="/var/log/nginx/"
    RECORD_TIME=$(date -d "yesterday" +%Y-%m-%d+%H:%M)
    PID=/var/run/nginx/nginx.pid
    mv ${LOG_PATH}/access.log ${LOG_PATH}/access.${RECORD_TIME}.log
    mv ${LOG_PATH}/error.log ${LOG_PATH}/error.${RECORD_TIME}.log
    #向Nginx主进程发送信号,用于重新打开日志文件
    kill -USR1 `cat $PID`
    
  2. 为 cut_nginx_log.sh 添加可执行的权限,并运行测试日志切割

    chmod +x cut_nginx_log.sh
    ./cut_nginx_log.sh
    
  3. 设置定时执行日志切割

    yum -y install crontabs
    # 1.查看当前的定时任务
    crontab -l
    # 2.添加定时任务,在打开的文件中输入:    */1 * * * * /usr/local/nginx/sbin/cut_nginx_log.sh
    crontab -e
    # 重启定时任务
    service crond restart
    
    # 定时任务常用命令:
    service crond start   #启动服务
    service crond stop    #关闭服务
    service crond restart #重启服务
    service crond reload  #重新载入配置
    crontab -e            #编辑任务
    crontab -l            #查看任务列表
    
    # 每分钟执行: */1 * * * *
    # 每天晚上执行:59 23 * * *
    # 每天凌晨执行:0 1 * * *
    ```shell
    yum -y install crontabs
    # 1.查看当前的定时任务
    crontab -l
    # 2.添加定时任务,在打开的文件中输入:    */1 * * * * /usr/local/nginx/sbin/cut_nginx_log.sh
    crontab -e
    # 重启定时任务
    service crond restart
    
    # 定时任务常用命令:
    service crond start   #启动服务
    service crond stop    #关闭服务
    service crond restart #重启服务
    service crond reload  #重新载入配置
    crontab -e            #编辑任务
    crontab -l            #查看任务列表
    
    # 每分钟执行: */1 * * * *
    # 每天晚上执行:59 23 * * *
    # 每天凌晨执行:0 1 * * *
    
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值