1. 完成nginx编译安装脚本
[root@ubuntu5 ~]#cat install_nginx.sh
NGINX_VERSION=1.12.1
NGINX_FILE=nginx-${NGINX_VERSION}.tar.gz
NGINX_URL=http://nginx.org/download/
NGINX_INSTALL_DIR=/apps/nginx
SRC_DIR=/usr/local/src
CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'`
. /etc/os-release
color () {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$1" && $MOVE_TO_COL
echo -n "["
if [ $2 = "success" -o $2 = "0" ] ;then
${SETCOLOR_SUCCESS}
echo -n $" OK "
elif [ $2 = "failure" -o $2 = "1" ] ;then
${SETCOLOR_FAILURE}
echo -n $"FAILED"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}
check () {
[ -e ${NGINX_INSTALL_DIR} ] && { color "nginx 已安装,请卸载后再安装" 1; exit; }
cd ${SRC_DIR}
if [ -e ${NGINX_FILE}${TAR} ];then
color "相关文件已准备好" 0
else
color '开始下载 nginx 源码包' 0
wget ${NGINX_URL}${NGINX_FILE}${TAR}
[ $? -ne 0 ] && { color "下载 ${NGINX_FILE}${TAR}文件失败" 1; exit; }
fi
}
install () {
color "开始安装 nginx" 0
if id nginx &> /dev/null;then
color "nginx 用户已存在" 1
else
useradd -s /sbin/nologin -r nginx
color "创建 nginx 用户" 0
fi
color "开始安装 nginx 依赖包" 0
if [ $ID == "centos" ] ;then
if [[ $VERSION_ID =~ ^7 ]];then
yum -y install gcc make pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
elif [[ $VERSION_ID =~ ^8 ]];then
yum -y install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
else
color '不支持此系统!' 1
exit
fi
elif [ $ID == "rocky" ];then
yum -y install gcc make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
else
apt update
apt -y install gcc make libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev
fi
[ $? -ne 0 ] && { color "安装依赖包失败" 1; exit; }
cd $SRC_DIR
tar xf ${NGINX_FILE}
NGINX_DIR=`echo ${NGINX_FILE}| sed -nr 's/^(.*[0-9]).*/\1/p'`
cd ${NGINX_DIR}
./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
make -j $CPUS && make install
[ $? -eq 0 ] && color "nginx 编译安装成功" 0 || { color "nginx 编译安装失败,退出!" 1 ;exit; }
chown -R nginx.nginx ${NGINX_INSTALL_DIR}
ln -s ${NGINX_INSTALL_DIR}/sbin/nginx /usr/local/sbin/nginx
echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
LimitNOFILE=100000
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now nginx &> /dev/null
systemctl is-active nginx &> /dev/null || { color "nginx 启动失败,退出!" 1 ; exit; }
color "nginx 安装完成" 0
}
check
install
2. 完成nginx平滑升级,总结步骤
当前装好nginx1.22.1,准备升级到1.24.0
查看防疫安装参数
下载新版1.24.0,并提供过同样的参数进行编译,但不需要执行install命令
![](https://i-blog.csdnimg.cn/direct/b60bdd5c1c6a437c92e1365c5a78047c.png)
![](https://i-blog.csdnimg.cn/direct/b8706782c2424fc983234129e60c67c5.png)
![](https://i-blog.csdnimg.cn/direct/553f5532bfbb4683be878858871f2b72.png)
![](https://i-blog.csdnimg.cn/direct/dcc4405d088d4edbab8930f64190d2d7.png)
![](https://i-blog.csdnimg.cn/direct/93ac6e41b8664d539f8972710e3a68c8.png)
![](https://i-blog.csdnimg.cn/direct/53899dfbdfa94eb89c8a9155d796d71b.png)
![](https://i-blog.csdnimg.cn/direct/023d8688a0d642c28b3425efa7635a62.png)
kill -HUP `cat /apps/nginx/logs/nginx.pid.oldbin`
kill -QUIT `cat /apps/nginx/logs/nginx.pid`
mv /opt/nginx.old /apps/nginx/sbin/
3. 总结nginx核心配置,并实现nginx多虚拟主机
主配置文件结构:四部分
main block:主配置段,即全局配置段,对http,mail都有效
#事件驱动相关的配置
event {
...
}
#http/https 协议相关配置段
http {
...
}
#默认配置文件不包括下面两个块
#mail 协议相关配置段
mail {
...
}
#stream 服务器相关配置段
stream {
...
}
nginx核心配置
#全局配置端,对全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,工作模式,Nginx的PID
路径,日志路径等。
user nginx nginx;
worker_processes 1; #启动工作进程数数量
events { #events设置快,主要影响nginx服务器与用户的网络连接,比如是否允许同时接受多个网络连
接,使用哪种事件驱动模型处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的
网络连接进行序列化等。
worker_connections 1024; #设置单个nginx工作进程可以接受的最大并发,作为web服务器
的时候最大并发数为worker_connections * worker_processes,作为反向代理的时候为
(worker_connections * worker_processes)/2
}
http { #http块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模
块都可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,
server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和单个链
接的请求上限等。
include mime.types;
default_type application/octet-stream;
sendfile on; #作为web服务器的时候打开sendfile加快静态文件传输,指定是否使用
sendfile系统调用来传输文件,sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操
作),从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝,硬盘 >>
kernel buffer (快速拷贝到kernelsocket buffer) >>协议栈。
keepalive_timeout 65; #长连接超时时间,单位是秒
server { #设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个location模块。比如
本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口,比如都使用80端口提供
web服务、
listen 80; #配置server监听的端口
server_name localhost; #本server的名称,当访问此名称的时候nginx会调用当前
serevr内部的配置进程匹配。
location / { #location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指
令,都是在location中体现的,主要是基于nginx接受到的请求字符串,对用户请求的UIL进行匹配,并对特
定的指令进行处理,包括地址重定向、数据缓存和应答控制等功能都是在这部分实现,另外很多第三方模块的
配置也是在location模块中配置。
root html; #相当于默认页面的目录名称,默认是安装目录的相对路径,可以使用绝对路
径配置。
index index.html index.htm; #默认的页面文件名称
}
error_page 500 502 503 504 /50x.html; #错误页面的文件名称
location = /50x.html { #location处理对应的不同错误码的页面定义到/50x.html,这个
跟对应其server中定义的目录下。
root html; #定义默认页面所在的目录
}
}
#和邮件相关的配置
#mail {
# ...
# } mail 协议相关配置段
#tcp代理配置,1.9版本以上支持
#stream {
# ...
# } stream 服务器相关配置段
#导入其他路径的配置文件
#include /apps/nginx/conf.d/*.conf
}
实现nginx多虚拟主机
修改nginx配置文件/apps/nginx/conf/nginx.conf
[root@ubuntu1 /data/nginx/html/pc]#vim /apps/nginx/conf/nginx.conf
#编辑文件行尾添加子配置文件
include conf.d/*.conf;
创建两个虚拟主机目录/data/nginx/html/{pc,mobile}
编辑创建两个虚拟主机页面
分别编辑两个虚拟主机配置文件
![](https://i-blog.csdnimg.cn/direct/3dc248d106b24d48ac4a328c3a354f42.png)
![](https://i-blog.csdnimg.cn/direct/a707aadb6135432fb7b0053ebc86a155.png)
![](https://i-blog.csdnimg.cn/direct/b46d75581e70430494f0d2ee139336f3.png)
![](https://i-blog.csdnimg.cn/direct/8b9a0cce16ce4d9382c4db8cffa85940.png)
4. 总结nginx日志格式定制
访问日志由 ngx_http_log_module 模块实现
日志格式的常见变量
$remote_addr # 记录客户端IP地址
$remote_user # 记录客户端用户名
$time_local # 记录通用的本地时间
$time_iso8601 # 记录ISO8601标准格式下的本地时间
$request # 记录请求的方法以及请求的http协议
$status # 记录请求状态码(用于定位错误信息)
$body_bytes_sent # 发送给客户端的资源字节数,不包括响应头的大小
$bytes_sent # 发送给客户端的总字节数$msec # 日志写入时间。单位为秒,精度是毫秒。
$http_referer # 记录从哪个页面链接访问过来的
$http_user_agent # 记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端IP地址
$request_length # 请求的长度(包括请求行,请求头和请求正文)。
$request_time # 请求花费的时间,单位为秒,精度毫秒
1)默认日志格式
http {
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 /var/log/nginx/access.log main;
2)自定义默认格式日志
如果是要保留日志的源格式,只是添加相应的日志内容,则配置如下:
#注意:此指令只支持http块,不支持server块
log_format access_log_format '$remote_addr - $remote_user [$time_local]
"$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'
'$server_name:$server_port';
#注意:此指令一定要在放在log_format命令后
access_log logs/access.log access_log_format;
#重启nginx并访问测试日志格式
==> /apps/nginx/logs/access.log <==
10.0.0.1 - - [22/Feb/2019:08:44:14 +0800] "GET /favicon.ico HTTP/1.1" 404 162 "-
" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/2
0100101 Firefox/65.0" "-"www.wang.org:80
3)自定义 json 格式日志
Nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中
通常将nginx日志转换为json日志,然后配合使用ELK做日志收集,统计和分析
log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,' #总的处理时间
'"upstreamtime":"$upstream_response_time",' #后端应用服务器处理时间
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",'
'"uri":"$uri",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';
access_log /apps/nginx/logs/access_json.log access_json;
4)编辑nginx配置文件设置文件格式
[root@ubuntu5 ~]#vim /apps/nginx/conf/nginx.conf
[root@ubuntu5 ~]#nginx -s reload #生效
![](https://i-blog.csdnimg.cn/direct/b8ae1a2b8f964f6e9c4c9c2922a18794.png)
5. 总结 nginx反向代理及https安全加密
Nginx 反向代理
反向代理 是代理服务器的一种,它接收客户端的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的响应返回给相应的客户端。
主要用途:
负载均衡:通过分配请求到服务器集群中的不同服务器,提高网站的可用性和性能。
缓存静态内容:减少源服务器的负载以及加快内容的传输速度。
SSL/TLS 终止:在代理层解密请求并将其以普通 HTTP 形式发送至内部服务器,增强安全性。
增强安全性:限制外界直接访问内部服务器,防止可能的攻击。
https安全加密
nginx 的https 功能基于模块ngx_http_ssl_module实现,因此如果是编译安装的nginx要使用参数
ngx_http_ssl_module开启ssl功能,但是作为nginx的核心功能,yum安装的nginx默认就是开启的,编
译安装的nginx需要指定编译参数–with-http_ssl_module开启
可通过nginx -V查看
6. 实验完成基于LNMP和Redis的phpmyadmin的会话保持,记录完整步骤
实验环境:
192.168.3.9 NGINX负载均衡器
192.168.3.8 NGINX+PHP-FPM部署phpMyadmin
192.168.3.10 NGINX+PHP-FPM部署phpMyadmin
192.168.3.20 部署MySQL和Redis
192.168.3.9部署NGINX负载均衡
# rocky8.8
yum install nginx -y
systemctl enable --now nginx
# 先去主配置删除掉default_server配置
vim /etc/nginx/nginx.conf
listen 80 default_server;
listen [::]:80 default_server;
改为
listen 80;
listen [::]:80;
# 写反向代理配置
vim /etc/nginx/conf.d/myadmin.conf
upstream myadmin {
server 192.168.3.8:80;
server 192.168.3.10:80;
}
server {
listen 80 default_server;
client_max_body_size 1024m;
# 在server配置块,location字块中,配置访问/的请求反向代理到myadmin服务器组中
location / {
proxy_pass http://myadmin;
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
nginx -s reload
192.168.3.20 部署MySQL和Redis
部署MySQL,redis
# rocky8
# 安装MySQL,redis
yum install mysql-server redis-server -y
systemctl enable --now mysqld redis
# 创建MySQL远程连接账户
mysql
mysql>create user admin@'192.168.3.%' identified by '123456';
mysql>grant all on *.* to admin@'192.168.3.%';
# 修改redis支持远程连接
# 把bind 127.0.0.1
# 修改为bind 0.0.0.0
vim /etc/redis.conf
bind 0.0.0.0
systemctl restart redis
[root@Rocky88-2 ~]# ss -ntpl | grep 6379
LISTEN 0 511 0.0.0.0:6379 0.0.0.0:* users:(("redis-server",pid=5369,fd=6))
[root@Rocky88-2 ~]#
192.168.3.8 NGINX+PHP-FPM部署phpMyadmin
192.168.3.10 NGINX+PHP-FPM部署phpMyadmin
分别部署NGINX、PHP-FPM、phpMyadmin、配置PHP会话信息redis保存
#ubuntu22.04
apt install nginx php8.1-fpm php-mysql php-redis php-mbstring php-json -y
systemctl enable --now nginx php8.1-fpm
#修改配置
vim /etc/nginx/sites-enabled/default
# 取消部分注释改成这样
index index.html index.htm index.nginx-debian.html index.php;
...
# pass PHP scripts to FastCGI server
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php-fpm (or other unix sockets):
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}
systemctl restart nginx php8.1-fpm
# 默认主目录/var/www/html/
部署phpmyadmin
cd /var/www/html/ # ubuntu22.04
curl -o phpMyAdmin-5.2.1-all-languages.tar.gz https://files.phpmyadmin.net/phpMyAdmin/5.2.1/phpMyAdmin-5.2.1-all-languages.tar.gz
tar -xf phpMyAdmin-5.2.1-all-languages.tar.gz
ln -s phpMyAdmin-5.2.1-all-languages/ phpmyadmin
修改phpmyadmin配置
cd /var/www/html/phpmyadmin
cp config.sample.inc.php config.inc.php
vim config.inc.php
# 第30行改为:
$cfg['Servers'][$i]['host'] = '192.168.3.20';
# 如果需要更改MySQL连接端口,需要增加该行
$cfg['Servers'][$i]['port'] = '3307';
chown -R www-data:www-data /var/www/html/
配置php使用redis保存session信息
vim /etc/php/8.1/fpm/php.ini
# 修改配置值
date.timezone = Asia/Shanghai
post_max_size = 100M
upload_max_filesize = 100M
# 文件最后加上配置
vim /etc/php/8.1/fpm/pool.d/www.conf
php_value[session.save_handler] = redis
php_value[session.save_path] = "tcp://192.168.3.20:6379"