nginx简单应用
1、nginx一键编译安装脚本
[root@rocky2 ~]#vim nginx_install.sh
#!/bin/bash
SRC_DIR=/data/nginx/
NGINX_URL=http://nginx.org/download/
NGINX_FILE=nginx-1.22.1
TAR=.tar.gz
NGINX_INSTALL_DIR=/apps/nginx
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
}
os_type () {
awk -F'[ "]' '/^NAME/{print $2}' /etc/os-release
}
os_version () {
awk -F'"' '/^VERSION_ID/{print $2}' /etc/os-release
}
check () {
[ -e ${NGINX_INSTALL_DIR} ] && { color "nginx 已安装,请卸载后再安装" 1; exit; }
cd ${SRC_DIR}
color "开始安装 nginx 依赖包" 0
if [ $ID == "centos" ] ;then
if [[ $VERSION_ID =~ ^7 ]];then
yum -y -q install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
elif [[ $VERSION_ID =~ ^8 ]];then
yum -y -q 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 -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
else
apt update &> /dev/null
apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
fi
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
cd $SRC_DIR
tar xf ${NGINX_FILE}${TAR}
NGINX_DIR=`echo ${NGINX_FILE}${TAR}| 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; }
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
KillSignal=SIGQUIT/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
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
[root@rocky2 ~]#systemctl enable --now nginx
[root@rocky2 ~]#ss -ntl
如果出现以下报错,留意是否关闭SElinux
sed -i '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config
reboot
#关闭SElinux后执行
sudo restorecon -rv /apps/nginx/sbin/nginx
2、nginx配置
官方帮助文档
http://nginx.org/en/docs/
配置文件
-
主配置文件:nginx.conf
-
子配置文件: include conf.d/*.conf,需要在主配置文件中用include的值指定文件,
如放在http语句块中,则指定文件中的内容必须要支持http语句块
-
fastcgi, uwsgi,scgi 等协议相关的配置文件
-
mime.types:支持的mime类型
2.1、全局配置
以root开启主进程,nginx账号开启子进程,因为80端口是特权端口,不允许普通用户监听
Main 块,全局配置段常见的配置指令分类
- 正常运行必备的配置
- 优化性能相关的配置
- 绑定进程到指定cpu核心
- 修改工作进程的数量
- 更改优先级
- 更改进程的最大并发连接数
- 关闭启用“惊群”
- 用于调试及定位问题相关的配置
- 事件驱动相关的配置
main块:指令不放在任何语句块中,就属于main块
指令:指令+值,中间空格隔开,空格个数没有需求,但必须以;分号结尾, worker_processes 1;
语句块中可以再嵌入语句块
3、搭建网站
nginx默认自带一个网站,需求不大直接配置即可,配置DNS指向可通过域名访问,默认在编译安装的目录下的/html/index.html
3.1、新建网站
单一主机搭建两个网站给pc和mobile
[root@centos8 ~]#mkdir /apps/nginx/html/{pc,mobile} -pv
[root@centos8 ~]#touch /apps/nginx/html/pc/index.html /apps/nginx/html/mobile/index.html #创建网站文件存放位置
[root@centos8 ~]#vim #编辑网站页面
[root@centos8 ~]#mkdir /apps/nginx/conf.d/ #创建便于管理的配置文件存放目录
[root@centos8 ~]#vim /apps/nginx/conf/conf/nginx.conf
# }
#}
include /apps/nginx/conf.d/*.conf; #可以在主配置文件中的http语句块的最后一个花括号前面指定单独使用的配置文件
}
[root@centos8 ~]#cd /apps/nginx/conf.d/
[root@centos8 conf.d]#vim pc.conf mobile.conf #注意文件以conf结尾
server {
listen 80; #可以不写,默认是80
server_name www.magedu.org; #网站名,需搭配DNS指向
root /apps/nginx/html/pc; #指定默认的网页文件
location /about { #单独访问该网站的about时去哪找网页文件
alias /opt/pc/aboutdir/; #指定about的网页文件
}
}
[root@centos8 conf.d]#nginx -t
[root@centos8 conf.d]#nginx -s reload
3.2、同一主机上搭建不同网站需留意网页文件的位置,谁在前谁优先级高
root和alias的区别:
location /about {
alias /opt/pc/aboutdir/; #访问网站的about时会在/opt/pc/aboutdir/下找网页文件
}
location /about {
root /opt/pc/aboutdir/; #访问网站的about时会在/opt/pc/aboutdir/下找about的网页文件
}
4、自定义日志格式
调用模块 ngx_http_log_module
默认格式
[root@centos8 ~]#vim /apps/nginx/conf/nginx.conf
http {
include mime.types;
default_type application/octet-stream;
log_format testlog '$remote_addr [$time_local] "$request" $status "$http_user_agent"';
#testlog自定义的日志格式的名称
#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;
server {
access_log /apps/nginx/logs/access-www.log testlog; #后续日志会以testlog格式写入到该目录下
}
4.1、自定义json格式日志
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;
#可以用jq工具整理json格式日志文件