从零开始的运维学习笔记4-nginx

nginx学习笔记
nginx的基础知识都有记录,适合快速掌握nginx,未来继续研究nginx也可以有知识依据

nginx官方文档:
https://nginx.org/en/docs/

1 nginx配置

1.1 配置yum源

#可在https://nginx.org/en/linux_packages.html查看配置
#vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$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/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
yum install -y nginx
rpm -qa|grep nginx
systemctl enable nginx
systemctl start nginx

1.2 nginx关键文件

目录/文件描述
/etc/nginx/nginx各种配置的目录
/etc/nginx/nginx.conf主配置文件
/etc/nginx/conf.d/子配置文件(网站)
/etc/nginx/conf.d/default.conf默认的子配置文件
/usr/sbin/nginxngx命令
/usr/share/nginx/html/ngx默认的站点目录,网站的根目录(可以通过查看配置得知)
/var/Log/nginx/ngx日志
目录/文件描述
/etc/logrotate.d/nginx日志切割,防止文件过大
/etc/nginx/mime.types媒体类型
/etc/nginx/fastcgi_params用于ngx+php的配置文件
/etc/nginx/uwsgi_params用于ngx+python的配置文件
/usr/lib/systemd/system/nginx.servicesystemctl配置文件
/var/cache/nginx/缓存目录

1.3 配置文件

1.3.1 简单配置

/etc/nginx/conf.d/test.oldboylinux.cn.conf

server {
  listen 80;
  server_name test.oldboylinux.cn;
  root /app/code/test;
  location / {
    index index.html;
  }
}
#检查语法
nginx-t
在windows中修改以下路径下的hosts文件,进行访问测试
C:\Windows\System32\drivers\etc

1.3.2 配置文件详解

主配置文件
请添加图片描述

子配置文件
请添加图片描述

1.4 http状态码

状态码含义
2xx表示正常
3xx表示要跳转,表示正常
4xx表示异常,客户端问题
5xx表示异常,服务端问题
状态码描述详情或原因
200OK访问正常
301Moved Permanently永久跳转
302Found或Moved Temporarily临时跳转
304Not Modified浏览器缓存
403Forbidden权限拒绝(拒绝访问)
404Not Found文件找不到,一般辅助错误日志排查
500Internal Error内部错误,SELinux开启,其他原因
502Bad Gateway网关错误,一般发生在负载中
503Service Unavailable服务临时不可用,后端负载异常等情况
504Gateway Time-out网关超时

1.5 常用测试命令

curl -Lv baidu.com
wget --debug baidu.com

2 虚拟主机

类别描述
基于域名的虚拟主机不同域名访问不同的站点。生产环境最常用的。(域名不同端口是80,443)
基于端口的虚拟主机不同端口访问不同的站点。保护,设置特殊端口。1024以上888818888
基于IP的虚拟主机不同IP访问不同的站点。用来限制网站只能通过指定的IP进行访问内网IP,VPN IP。

2.1 基于域名的虚拟主机(主)

站点名称域名站点目录代码文件名
FC小霸王怀旧游戏机game.oldboylinux.cn/app/code/gameFC小霸王怀日游戏机-HTML源码.zip
黄金矿工mine.oldboylinux.cn/app/code/minemine.zip
打字游戏type.oldboylinux.cn/app/code/typetype-game.zip

/etc/nginx/conf.d/game.oldboylinux.cn.conf

server {
  listen 80;
  server_name game.oldboylinux.cn;
  root /app/code/game;
  location / {
    index index.html;
  }
}

/etc/nginx/conf.d/mine.oldboylinux.cn.conf

server {
  listen 80;
  server_name mine.oldboylinux.cn;
  root /app/code/mine;
  location / {
    index index.html;
  }
}

测试

curl -v -H "Host: game.oldboylinux.cn" http://10.0.0.7/index.html

2.2 基于端口的主机

server {
  listen 81;
  server_name live.oldboylinux.cn;
  root /app/code/game;
  location / {
    index index.html;
  }
}
curl -H Host:live.oldboylinux.cn http://10.0.0.7:81/index.html

2.3 基于ip的虚拟主机

双网卡主机,设置只能通过某个ip访问

server {
  listen 172.16.1.7:8848;
  server_name game.oldboylinux.cn;
  root /app/code/game;
  location / {
    index index.html;
  }
}
nginx -t
systemctl restart nginx
curl -H Host:game.oldboylinux.cn http://10.0.0.7:8848
curl -H Host:game.oldboylinux.cn http://172.16.1.7:8848

3 nginx日志

类型定义使用场景使用建议
错误日志发生故障的时候可以查看记录4xx,5xx错误通过错误级别指定
访问日志记录着用户什么时候访问网站页面访问和客户端信息通过Log_format定义格式

3.1 错误日志

error_log指令
格式:error_log 文件名 错误日志级别;
指令放在哪:main , http , mail , stream , server , location
错误日志级别;:左到右,越来越粗糙. 记录信息的详细程度.
debug, info, notice, warn, error, crit, alert, emerg.
error		是默认的.
notice 		推荐.
debug: 		未来用于调试使用,短时间开启,网站访问量较大别开.
生产建议
- 给每个虚拟主机指定自己独立的错误日志.
- 将nginx.conf里的error_log注释掉
server {
  listen 80;
  server_name game.oldboylinux.cn;
  error_log /var/log/nginx/game.oldboylinux.cn-error.log notice;
  root /app/code/game;
  location / {
    index index.html;
  }
}

3.2 访问日志

3.2.1 使用示范

access_log		指定访问日志
access_log 		日志位置 格式
放在哪:http , server , location , if in location , limit_except
生产建议
- 给每个虚拟主机指定自己独立的访问日志.
- 将nginx.conf里的access_log注释掉

请添加图片描述

server {
  listen 80;
  server_name game.oldboylinux.cn;
  error_log /var/log/nginx/game.oldboylinux.cn-error.log notice;
  access_log /var/log/nginx/game.oldboylinux.cn-access.log main;
  root /app/code/game;
  location / {
    index index.html;
  }
}

3.2.2 nginx内置变量

内置变量说明
$remote_addr客户端IP地址
$remote_user用户名(如果ngx进行认证,则为空)
$time_local时间,格式如:30/Aug/2022:14:44:27 +0800
$request请求报文的起始行,包括请求方法、URI和HTTP版本(如:GET / HTTP/1.1)
$statusHTTP状态码
$body_bytes_sent响应给客户的文件的大小(单位:字节)
$http_referer引用页,即用户从哪个页面跳转而来
$http_user_agent用户代理(UA),即客户端浏览器信息
$http_x_forwarded_forXFF头,负载均衡中使用,记录用户真实的IP地址

更多nginx内置变量:
http://nginx.org/en/docs/varindex.html

3.2.3 访问日志选项补充

access_log说明
访问日志进行压缩gzip需要通过zcat/zless/zgrep查看
进行缓存buffer=32k 先把日志写入内存,再写入磁盘
定义刷新时间flush=10s
server {
  listen 80;
  server_name game.oldboylinux.cn;
  error_log /var/log/nginx/game.oldboylinux.cn-error.log notice;
  access_log /var/log/nginx/game.oldboylinux.cn-access.log main gzip buffer=32k flush=10s;
  root /app/code/game;
  location / {
    index index.html;
  }
}

4 location规则

4.1 url和uri

http://www.baidu.com/lidao/lidao.avi
URI: /lidao/lidao.avi 域名后面的内容
URL: http://www.baidu.com/lidao/lidao.avi 网址

4.2 location规则

Location规则说明
location /默认规则,保底。当其他规则都匹配失败时,匹配默认的规则。
location /image/用于匹配请求的URI(路径)。例如:cxk.oldboylinux.cn/image/lidao.txt
location ~ (jpg/jpeg)$ {}支持正则,区分大小写。例如:cxk.oldboylinux.cn/Lidao/lidao.jpg
location ~* (jpg/jpeg)$ {}支持正则,不区分大小写。例如:cxk.oldboylinux.cn/lidao/lidao.jpg (jpg/jpeg)$
location ^~不支持正则,仅匹配普通字符,很少使用,优先级较高。
location =不支持正则,精确匹配,使用较少。
location @命名的Location,一般用于returnerror_log跳转。
优先级符号
1=
2^~
3~ ~*
4/image/
5/

4.3 location案例1

域名:buy.oldboylinux.cn
站点目录:/app/code/buy/ 首页文件index.html  
后台管理页面:/app/code/buy/admin/index.html
要求后台admin只能内网访问:172.16.1.0/24网段.
server {
  listen 80;
  server_name buy.oldlinux.cn;
  root /app/code/buy;
  location / {
    index index.html;
  }
  location /admin/ {
    allow 172.16.1.0/24;
    deny all;
  }
}

4.4 location案例2

给网站加速,设置缓存,网站中html,js,css结尾的文件缓存1天,图片缓存1小时.
server {
  listen 80;
  server_name bird.oldboylinux.cn;
  root /app/code/bird;
  location / {
    index index.html;
  }
  location ~* \.(html|js|css)$ {
    expires max;
  }
  location ~* \.(jpg|jpeg|png|gif|bmp)$ {
    expires 1h;
  }
}

4.5 location案例3

/app/code/china/
china.oldboylinux.cn
如果访问.js文件 访问/app/code/china/js
如果访问.css文件 访问/app/code/china/css
server {
  listen 80;
  server_name china.oldboylinux.cn;
  root /app/code/china;
  location / {
    index index.html;
  }
  location ~* .js$ {
    expires 1d;
    root /app/code/china/js;
  }
  location ~* .js$ {
    expires 10d;
    root /app/code/china/css;
  }
}

4.6 autoindex案例

4.6.1 autoindex模块

设置项描述
autoindex on开启目录索引功能,显示站点目录下的文件列表(首页文件不存在时)。
autoindex_localtime on显示文件的本地时间。
autoindex_exact_size off是否显示精确的文件大小。off表示以人类可读形式显示大小。

4.6.2 增加统计功能

    location /status {
        stub_status;
    }

4.6.3 添加密码

yum install -y httpd-tools
#创建文件
htpasswd  -bc /etc/nginx/user   lidao996  1
#增加用户
htpasswd  -b /etc/nginx/user   oldboy  1
#修改权限
chmod 600 /etc/nginx/user
chown nginx.nginx /etc/nginx/user

4.6.4 完整配置

server {
    listen 80;
    server_name v.oldboylinux.cn;
    root /app/code/v;
    error_log /var/log/nginx/test-error.log notice;
    access_log /var/log/nginx/test-access.log main;
    charset utf8;
    autoindex on;
    autoindex_localtime on;
    autoindex_exact_size off;
    location / {
        index index.html;
    }
    location /svip/ {
      auth_basic "input password:";
      auth_basic_user_file /etc/nginx/user;
    }
    location /status {
        stub_status;
    }
}

5 部署lnmp-以wordpress为例

linux+nginx+mysql+php

5.1 数据库端部署

yum install -y mariadb-server
systemctl enable mariadb
systemctl start mariadb
ss -lntup|grep mysql
ps -ef|grep mysql
#仅首次运行
mysql_secure_installation
mysql -uroot -p1
create database wordpress;
grant all on wordpress.* to 'wp'@'localhost' identified by 'wp';
grant all on wordpress.* to 'wp'@'10.0.0.%' identified by 'wp';

连接测试

mysql -uwp -pwp -h 10.0.0.104

5.2 php端部署

清理已有PHP包

systemctl stop php-fpm
yum -y remove php*
yum remove remi-release.noarch

配置php 7.4 yum源

yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm

下载php全家桶

yum -y install php74 php74-php-bcmath php74-php-cli php74-php-common php74-php-devel php74-php-embedded php74-php-fpm php74-php-gd php74-php-intl php74-php-mbstring php74-php-mysqlnd php74-php-opcache php74-php-pdo php74-php-pear php74-php-pecl-igbinary php74-php-pecl-memcached php74-php-process php74-php-xml php7.4-redis
systemctl enable php74-php-fpm
systemctl start php74-php-fpm
/etc/opt/remi/php74/php-fpm.conf   #主配置文件
/etc/opt/remi/php74/php-fpm.d
/etc/opt/remi/php74/php-fpm.d/www.conf #子配置文件,修改目标
[root@web01 ~]# egrep -n '^(user|group)' /etc/opt/remi/php74/php-fpm.d/www.conf
24:user = nginx
26:group = nginx
[root@web01 ~]# systemctl restart php74-php-fpm.service

5.3 nginx配置

server {
  listen 80 default_server;
  server_name blog.oldboylinux.cn
  root /app/code/blog
  error_log /var/log/nginx/blog-error.log notice;
  access_log /var/log/nginx/blog-access.log main;

  location / {
    index index.php;
  }

  location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_buffering on;
    fastcgi_buffers 64 64k;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }
}

5.4 接入NFS

cd /app/code/blog/wp-content/
mv uploads/ uploads-bak
cd /app/code/blog/wp-content/
mkdir -p uploads/
mount -t nfs 10.0.0.103:/uploads/wordpress /app/code/blog/wp-content/uploads

5.5 排错与调试

5.5.1 测试nginx能否正确解析

<?php
phpinfo();
?>

5.5.2 测试web机能否连接数据库

<?php
$db_host='10.0.0.104';
$db_user='wp';
$db_pass='1';
$db_name="wordpress";
$link_id=mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($link_id){
	echo "mysql success";
}else{
	echo "connection failed";
}
?>

6 负载均衡

6.1 实验准备

环境-
域名:lb.oldboylinux.cn站点目录 :/app/code/lb/index.html
负载均衡lb0110.0.0.5
web服务web0110.0.0.7
web服务web0210.0.0.8

6.2 web端

/etc/nginx/conf.d/lb.oldboylinux.cn.conf

server {
  listen 80;
  server_name lb.oldboylinux.cn;
  error_log /var/log/nginx/lb-error.log notice;
  access_log /var/log/nginx/lb-access.log main;
  root /app/code/lb;
  location / {
    index index.html;
  }
}

测试

curl -H host:lb.oldboylinux.cn http://10.0.0.7
curl -H host:lb.oldboylinux.cn http://10.0.0.8

6.3 负载端

/etc/nginx/conf.d/lb.oldboylinux.cn.conf

upstream lb_pools {
  #ip_hash;
  server 10.0.0.7:80;
  server 10.0.0.8:80;
}
server {
  listen 80 default_server;
  server_name lb.oldboylinux.cn;
  error_log /var/log/nginx/lb-error.log notice;
  access_log /var/log/nginx/lb-access.log main;
  location / {
    proxy_pass http://lb_pools;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-Ip $remote_addr;
    proxy_buffering on;
    proxy_buffer_size 128k;
    proxy_busy_buffers_size 256k;
    proxy_buffers 32 128k;
    }
}

6.4 负载均衡的模块选项

upstrem pools {
  server 10.0.0.7:80  weight=1 max_fails=3 fail_timeout=10s;
  server 10.0.0.8:80  weight=1 max_fails=3 fail_timeout=10s;
  server 10.0.0.9:80  weight=1 max_fails=3 fail_timeout=10s;
  server 10.0.0.10:80 backup weight=1 max_fails=3 fail_timeout=10s;
  server 10.0.0.11:80 backup weight=1 max_fails=3 fail_timeout=10s;
}
选项说明
weight权重,根据权重ngx分配请求。在代码更新与测试时,给测试服务器较小的权重。
max_failsngx具备健康检查功能,指定失败的次数,超过这个次数就认为节点挂了。一般情况下可以设置1-3。
fail_timeout认为节点挂了后间隔多久再次检查健康情况。默认是10s,可以根据要求设置时间,可以长一些,如30s/60s。
backup备胎服务器,当其他所有服务器都挂了的时候,才启用。使用时需要考虑雪崩的情况。

6.5 会话保持

  • 登录状态写入cookie中.(wordpress)
  • cookie+session方式 + 统一存放session服务器(会话保持服务器)
  • 通过认证服务实现Oauth 2.0(使用token方式)
  • ip_hash方法(讲解负载均衡轮询算法)

详情看讲义

6.6 轮询算法

负载均衡方法说明
rr(轮询)默认的循环访问方式。
wrr(加权轮询)加权轮询,在轮询的基础上增加权重功能。server中的weight就是加权轮询
ip_hash客户端IP和后端节点IP哈希,只要一样,就会一直访问同一个Web服务器。解决会话保持/会话共享问题,可能导致负载不均。
url_hash只要用户访问的URL相同,就访问相同的Web服务器。
least_conn最小连接数,LC算法。也可以配合权重使用,如wlc(权重的最小连接数)。
一致性hash算法需要自行研究。

ip_hash

将ip_hash;填入upstream即可

url_hash

hash $request_uri;

6.7 tengine

淘宝基于nginx二次开发

6.7.1 编译安装

yum install -y wget libssl-dev make gcc pcre2-utils libpcre3-dev zlib1g-dev
wget -P /tmp/ http://tengine.taobao.org/download/tengine-3.0.0.tar.gz
cd /tmp
tar xf tengine-3.0.0.tar.gz
cd tengine-3.0.0
# 如果用nginx升级成tengine,先nginx -v可以得到如下参数,再add-module选择需要的模组即可

./configure --prefix=/app/tools/tengine-3.0.0 \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_mp4_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--add-module=modules/ngx_http_upstream_check_module/ \
--add-module=modules/ngx_http_upstream_session_sticky_module
cd /tmp/
cd tengine-3.0.0
make -j `nproc`
make install
groupadd nginx
useradd -g nginx nginx
ln -s /app/tools/tengine-3.0.0 /app/tools/tengine
ln -s /app/tools/tengine/sbin/nginx /sbin/
#根据我们设置的路径,主配置文件在这里:
/app/tools/tengine/conf/nginx.conf
#我们新建/app/tools/tengine/conf/conf.d文件夹
#并在主配置文件的http模块中写入:
    include   /app/tools/tengine/conf/conf.d/*.conf;

- nginx升级tengine

# 如果用nginx升级成tengine,先nginx -V可以得到如下参数,再add-module选择需要的模组即可(-V是大写V)

./configure --prefix=/app/tools/tengine-3.0.0 \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_mp4_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--add-module=modules/ngx_http_upstream_check_module/ \
--add-module=modules/ngx_http_upstream_session_sticky_module
mv /sbin/nginx /sbin/nginx-1.24.0
mv /app/tools/tengine/sbin/nginx root@10.0.0.6:/sbin/
nginx -V

6.7.2 状态检查模块

指令说明
check指定检查频率,失败次数,成功次数,检查超时,检查方式。
check_http_send通过HTTP方式发出请求报文,包括请求报文起始行,请求方法,请求的URI,请求协议。
check_http_expect_alive收到指定的状态码,就认为是存活的。
check_status开启负载均衡状态检查功能,可以在web页面的Location使用以加强安全。
upstream lb_pools2 {
  #ip_hash;
  server 10.0.0.103:80 weight=1 max_fails=3 fail_timeout=30s; 
  server 10.0.0.105:80 weight=1 max_fails=3 fail_timeout=30s;
  check interval=3000 rise=2 fall=5 timeout=1000 type=http;
  check_http_send "HEAD / HTTP/1.0\r\nHost: phpadmin.zht.com.com\r\nUser-Agent: lb_check\r\n\r\n";
  check_http_expect_alive http_2xx http_3xx;
}
server {
  listen 80;
  server_name phpadmin.zht.com.com;
  error_log /var/log/nginx/phpadmin-error.log notice;
  access_log /var/log/nginx/phpadmin-access.log main;
  location / {
    proxy_pass http://lb_pools;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
location /lb_status {
  check_status;
  access_log off;
  allow 10.0.0.0/24;
  deny all;
}
}

7 四层负载均衡

四层负载均衡是基于端口的负载均衡

检查是否有相关模块

nginx -V|& grep stream

主配置文件nginx.conf相关配置(在最高层加入配置)

stream {
  upstream l4_pools {
    server 10.0.0.7:8848;
    server 10.0.0.8:8848;
  }
  server {
    listen 8848;
    #error_log
    #access_log
    proxy_pass l4_pools;
  }
}

8 nginx平滑升级

  • 平滑升级:不重启nginx升级nginx
  • 步骤:
    • 把当前环境nginx命令备份,用新的替换
    • 把当前运行的ngx的pid文件改个名,使用新的nginx命令启动nginx进程
    • 调试测试,关闭旧的nginx进程

环境准备

旧nginx:/sbin/nginx
新nginx:/tmp/nginx
#检查环境
nginx -v
#启动旧nginx
systemctl start nginx
ps -ef|grep nginx
#查看pid
ll /var/run/nginx.pid*
#备份ngx命令,替代ngx命令
mv /sbin/nginx /sbin/nginx-bak
mv /tmp/nginx /sbin/nginx
nginx -V
#准备新老交替
kill -USR2 `cat /var/run/nginx.pid`
ll /var/run/nginx.pid*
cat /var/run/nginx.pid.oldbin
kill 7404

9 rewrite功能

9.1 相关指令

指令说明
rewrite实现对URL的改写,使用正则匹配uri,进行改写。
return实现对URL的改写,通常与ngx变量一起使用。返回指定的状态码。无法使用正则表达式。
set创建或修改ngx变量。
if判断条件,通常与ngx变量一起使用。增强版本的LocationLocation用于匹配请求的URI。

9.2 return指令

返回状态码

server {
 listen 80;
 server_name rewrite.oldboylinux.cn;
 root /app/code/rewrite;
 location / {
   index index.html;
 }
  #location ~* (\.ini|\.pass)$ {
 location /admin/ {
   return 403;
 }
}

跳转地址

server {
 listen 80;
 server_name rewrite.oldboylinux.cn;
 return 301 http://www.baidu.com;
}

http跳https

server {
   listen 80;
   server_name rewrite.oldboylinux.cn;
   return 302 https://rewrite.oldboylinux.cn$request_uri;
}
server {
   listen 443 ssl;
   server_name rewrite.oldboylinux.cn;
   #私钥
   #公钥
   root /app/code/rewrite/;
   location / {
        index index.html;
   }
}

9.3 nginx中的if

  • 可放在server,location中
server {
 listen 80;
 server_name rewrite.oldboylinux.cn;
 root /app/code/rewrite ;
  if ( $request_method !~ "GET|POST" ) {
     return 403;
 }
 location / {
   index index.html;
 }
}

9.4 set

server {
 listen 80;
 server_name rewrite.oldboylinux.cn;
 set $url $http_host$request_uri;
 return 200 "$url\n";
}

用flag标记网站是否维护

server {
 listen 80;
 server_name rewrite.oldboylinux.cn;
 root /app/code/rewrite;
  set $flag 0;
  #include conf.d/rewrite-status.var;
  if ( $flag = 1 ) {
   return 503;
 }
 location / {
   index index.html;
 }
}

9.5 rewrite

支持正则,实现替换功能,替换url内容

标记说明
redirect302 临时重定向。用户访问时收到302提示及新位置的Location(响应头),用户根据Location新位置进行访问(让用户重新发出HTTP请求)。
permanent301 永久重定向。用户访问时收到301提示及新位置的Location(响应头),用户根据Location新位置进行访问(让用户重新发出HTTP请求),旧地址不再使用。
break用户请求匹配到包含break指令或rewrite规则后,即使后面还有Location规则,也不会继续运行,终止运行。
Last用户请求匹配到包含Last标记的rewrite规则后,停止继续执行,Nginx会重新发出内部请求,请求与Location规则进行匹配。
server {
 listen 80;
 server_name rewrite.oldboylinux.cn;
  #return 301 http://www.baidu.com$request_uri;
  #http://rewrite.oldboylinux.cn/images/lidao.txt
  #http://rewrite.oldboylinux.cn
 rewrite ^(.*)$ http://www.baidu.com$1 redirect;
}
server {
   listen 443 ssl;
   server_name rewrite.oldboylinux.cn;
   #私钥
   #公钥
   root /app/code/rewrite/;
   location / {
        index index.html;
   }
}

10 nginx优化

https://nginx.org/en/docs/

10.1 安全优化

请添加图片描述
请添加图片描述

- 1)隐藏nginx版本信息

[root@nginx /etc/nginx]$ curl -I 10.0.0.210
HTTP/1.1 200 OK
Server: nginx/1.26.0
...

# 在http模块中添加server_tokens off
[root@nginx /etc/nginx]$ cat nginx.conf
http {
    server_tokens off;
...
}

[root@nginx /etc/nginx]$ systemctl restart nginx
[root@nginx /etc/nginx]$ curl -I 10.0.0.210
HTTP/1.1 200 OK
Server: nginx
...


- 2) 修改web服务的名字版本

# 编译安装前修改
代码解压后目录下./src/core/nginx.h
代码解压后目录下./src/http/ngx_http_header_filter_module.c
代码解压后目录下./src/http/ngx_http_special_response.c

egrep -n "NGINX_(VERSION|VAR)" src/core/nginx.h
13:#define NGINX_VERSION "1.18.0" 14:#define NGINX_VER "nginx/" NGINX_VERSION
29:#define NGINX_VAR "NGINX" 

grep -n 'Server: nginx' src/http/ngx_http_header_filter_module.c
53:static u_char ngx_http_server_string[] = "Server: nginx" CRLF;

grep 'center.*nginx' src/http/ngx_http_special_response.c
"<hr><center>nginx</center>" CRLF

yum install -y openssl-devel pcre-devel #devel development 软件相关开发

- 4) 设置用户上传大小

# nginx的配置
# 写在主配置文件的http模块里全局生效
# 写在辅配置文件里单站生效
client_max_body_size 50m;
# php配置
/etc/opt/remi/php74/php.ini
694 post_max_size = 5M
846 upload_max_filesize = 50M

- 5)日志切割或日志轮询

日志切割使用的命令:
logrotate -f /etc/logrotate.d/nginx
# /etc/logrotate.d/nginx 配置日期切割的. #默认是系统定时任务调用,自己书写 crontab -e
[root@web01 /etc/nginx]# ll /etc/cron.daily/
总用量 8
-rwx------. 1 root root 219 4 月 1 2020 logrotate
-rwxr-xr-x. 1 root root 618 10 月 30 2018 man-db.cron
#日志切割的配置的格式

[root@web01 /etc/nginx]# cat /etc/logrotate.d/nginx
#指定被切割的文件. 
/var/log/nginx/*.log {
#每天切割 1 次. daily
#文件不存在不报错。
missingok
#循环 52 次 从第 53 此开始删除旧的切割。
rotate 52
#对日志进行压缩
compress
#延后 1 天进行压缩
delaycompress
#not if empty 如果文件为空不切割。
notifempty
#切割后文件的权限 所有者 用户组信息
create 640 nginx adm
#切割之后运行指定的命令 一般是重启的命令。
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid` fi
endscript
}

带缩进的纯净版

/var/log/nginx/*.log {
        daily
        missingok
        rotate 52
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

- 6 )对用户请求的 URI 进行访问控制

location /admin/ {
  return 403; #或者 deny all;
}

- 7 )什么是盗链:网站中盗取其他人网站的资源连接.

1. 方法加水印. 2. 通过 referer 头判断.用户间接访问就会有这个头部信息. 3. 配置认证,登录后才能用. 
if ( $http_referer ~"img.oldboylinux.cn") {
  return 403;
}
https://www.processon.com/view/link/648a862049c3ea6f1515fed6
- 被盗链网站配置
server {
  listen 80 default_server;
  server_name localhost;
  charset utf8;
  autoindex on;
  if ( $http_referer ~* "hack.oldboylinux.cn" ) {
    return 403;
  }
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
  }
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
    root /usr/share/nginx/html;
  }
}
- 攻击者网站
[root@web01 /etc/nginx/conf.d]# cat hack.oldboylinux.cn.conf
server {
  listen 80;
  server_name hack.oldboylinux.cn;
  root /app/code/hack;
  charset utf8;
  location / {
    index index.html;
  }
}
[root@web01 /etc/nginx/conf.d]# cat /app/code/hack/index.html
<html>
下载了一个网站的视频
<img src="http://10.0.0.7/lidao.png">
</html>

- 8 ) 错误页面的优雅展示

error_page 501 502 503 504 /50x.html;
location = /50x.html {
root /app/code/error/;
}
error_page 400 401 402 403 404 405 406 407 408 409 410 412 413 414 415 /40x.html;
location = /40x.html {
root /app/code/error/;
}
#在 return 如何指定错误提示的页面
set $flag 1;
if ( $flag = 1) {
return 503 http://lb.oldboylinux.cn/50x.html;
}
#404 页面:
https://volunteer.cdn-go.cn/404/latest/404.html

- 9 ) Nginx 站点目录文件及目录权限优化

权限推荐设置:
整个站点目录 文件 644 目录 755 属于 root root
如果涉及上传 文件 644 目录 755 属于 www www (中间件运行的用户)
时刻盯着临时目录/tmp/
给网站设置 md5sum 校验.网站每次更新后重新做下 md5. find /app/code/blog/ -type f |xargs md5sum >/backup/blog.md5
定时任务定期执行
md5sum -c --quiet /backup/blog.md5 2>/dev/null |wc -l
可以把结果保存到文件中文件包含主机名 ip 地址时间.txt
传输到 backup 服务器. 检查是否有新增加的文件. [root@web01 /app/code/lb]# find /app/code/blog/ -type f |wc -l
3074
课后研究 aide 命令.

- 10 ) nginx防爬虫优化

什么是爬虫?
通过命令,软件下载网站的指定的信息. curl/wget. 登录功能,验证码功能.python,golang. 
如何防爬?
1. 君子协议.robots.txt spider 或 bot
2. 在 ngx 中通过 ua 变量进行判断,手动屏蔽爬虫. 运营搜索引擎的爬虫爬取你的网站. 
3. 增加登录,认证功能,验证码. 
4. 访问频率限制.
server {
  #下面的屏蔽容易导致误杀,一些搜索引擎的爬虫,未来想精确,写出具体不想要的爬虫即可. 
  if ($http_user_agent ~* "spider|bot|curl|wget" ){
    return 403 ;
  }
  if ($http_user_agent !~* "baidu|google|android|ios|windows" ){
    return 403;
  }
  
  
意义不大,可以直接修改UA头绕过

- 11 ) 利用 Nginx 限制请求访问

用户请求方法限制 GET,HEAD,POST,PUT,DELETE,OPTIONS. 
if ( $http_method !~ "GET|HEAD|POST" ) { 
  return 403 http://lb.oldboylinux.cn/40x.html; #或 deny all;
}

- 12 ) Nginx监牢模式

监牢模式:通过普通用户运行与管理指定的服务. 
这里的用户是普通用户,非虚拟用户.这个用户可以登录系统. 
一般编译安装的软件(可以安装到指定目录--prefix=/app/tools/nginx/).
还可以是二进制软件. 
如果是 ngx 还有个坑,1-1024 范围的端口特权端口,只能 root 管理.

- 13 ) 限速 limit_rate

# 限制下载速度. 
# 可写在http模块里
limit_rate 100k;


#map 类似if 
map $slow $rate {
  1 4k; #如果$slow 的值是 1 则$rate 的值是 4k
  2 8k; #如果$slow 的值是 2 则$rate 的值是 8k
}
limit_rate $rate;

10.2 性能优化

请添加图片描述
请添加图片描述

-1 )ngx工具人用户数量

# 写在主模块
worker_processes 8; #cpu 核心总数

-2 )ngx CPU亲和力

# 写在主模块
worker_cpu_affinity auto;

-3 ) ngx io模型

apache 使用的模型: select 模型,同步模型. 
nginx 高性能模型: epoll 模型,异步模型,高并发. 
修改 ngx 主配置文件中的 events 区域即可
events { 
  use epoll; #<==增加这个
  worker_connections 1024;
}

-4) 优化 nginx 单工具人进程客户端连接数

每个 worker 进程可以同时处理的最大连接数. events 区域中
worker_connections 100000; # <==准备节点然后压力测试.

-5 ) 配置gzip压缩实现性能优化

# 写在http模块中
# 给静态资源进行压缩,节约带宽.对静态文字资源进行压缩,html,css,js,文字内容.其他静态资源图片,视频不推荐使用 gzip 压缩. gzip on;
gzip on;
gzip_min_length 1k; #设置大于 1K 才进行压缩
gzip_buffers 4 16k; #设置压缩缓存 4 个每个 16k
#gzip_http_version 1.0;
gzip_comp_level 2; #压缩级别 数字越大 压缩率(占用空间)越小 占用 CPU 越多
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php; 
#哪些类型的文件 需要进行压缩 这些类型需用 mime type 媒体类型. #mime types #媒体类型(http) === 文件类型(linux)
故障案例:
NSES WITH THE “TEXT/HTML” TYPE ARE ALWAYS COMPRESSED.
GZIP 默认压缩 TEXT/HTML 类型,不用指定,指定会报错。

-6) 配置 Nginx brotli 压缩实现性能优化

# 在http模块中填写,nginx默认无brotli模块,需要下载编译安装
# github.com/google/ngx_brotli网站内有安装指令
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;

-7) 优化nginx服务进程打开文件数

Linux 文件描述符,用于控制每个进程最多可以打开多少文件. 这个值分为 2 个部分:
1. 系统的设置. [root@web01 ~]# egrep -v '^$|#' /etc/security/limits.conf 
* soft nofile 65535
* hard nofile 65535
[root@web01 ~]# ulimit -n 65535
2. 服务软件的设置. ngx 主配置文件
user www;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 60000;
use epoll;
}

-8)配置Nginx expires实现让客户端缓存数据

设置静态资源在客户端浏览器中缓存. 图片 类
html,css,js 类
缓存时间设置,变化少,改动少的就可以增加缓存时间缓存 1 天或 10 天.
经常变动的缓存较短 1 小时
location ~* \.(gif|jpg|jpeg|png|bmp|ico)$ {
root /var/www/img/;
expires 30d;
#access_log off;
}

-9 ) timeout

一般表示超时时间,连接的时候时间,超过这个时间未完成连接,//连接. 
proxy_connect_timeout 连接超时时间. 
proxy_read_timeout 定义从代理服务器读取响应的超时. 适当可以加长 300s. 
proxy_send_timeout 设置将请求传输到代理服务器的超时。适当可以加长 300s.
  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值