02. Nginx入门-Nginx安装

Nginx安装

yum安装

编辑yum环境

cat > /etc/yum.repos.d/nginx.repo << 'EOF'
[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=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF

安装Nginx

yum list | grep nginx
yum -y install nginx
nginx -v

常用命令

#Nginx状态
systemctl status nginx
#关闭Nginx
systemctl stop nginx
#启动Nginx
systemctl statrt nginx
#重载Nginx
systemctl daemon-reload
#设置开机启动
systemctl enable nginx
#查看版本
nginx -v
nginx -V

源码安装

解决依赖环境

yum -y install gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel wget vim

安装Nginx

useradd nginx
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz -C /usr/local/
cd /usr/local/nginx-1.24.0
./configure --prefix=/usr/local/nginx \
--user=nginx --group=nginx \
--with-http_realip_module \
--with-http_v2_module \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-stream \
--with-stream_ssl_module \
--with-http_sub_module
echo $?
make install
echo $?
/usr/local/nginx/sbin/nginx -v

常用命令

#启动Nginx
/usr/local/nginx/sbin/nginx
#检查配置文件
/usr/local/nginx/sbin/nginx -t
#关闭Nginx
/usr/local/nginx/sbin/nginx -s stop
#重载Nginx
/usr/local/nginx/sbin/nginx -s reload
#查看版本
/usr/local/nginx/sbin/nginx -v
/usr/local/nginx/sbin/nginx -V

启动文件

cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

编译模块详解

查看编译模块命令

nginx -V

编译模块详解

--prefix=/etc/nginx																					#指定Nginx安装目录
--sbin-path=/usr/sbin/nginx																	#指定Nginx执行文件目录
--modules-path=/usr/lib64/nginx/modules											#指定Nginx模块路径
--conf-path=/etc/nginx/nginx.conf														#指定Nginx配置文件路径
--error-log-path=/var/log/nginx/error.log										#指定Nginx错误日志路径
--http-log-path=/var/log/nginx/access.log										#指定Nginx访问日志路径
--pid-path=/var/run/nginx.pid																#指定Nginx进程号存放路径
--lock-path=/var/run/nginx.lock															#指定Nginx启动锁定文件路径
--http-client-body-temp-path=/var/cache/nginx/client_temp		#指定Nginx客户端缓存路径
--http-proxy-temp-path=/var/cache/nginx/proxy_temp					#指定Nginx代理缓存路径
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp			#指定Nginx php缓存路径
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp					#指定Nginx python缓存路径
--http-scgi-temp-path=/var/cache/nginx/scgi_temp						#指定Nginx
--user=nginx																								#指定Nginx程序的用户
--group=nginx																								#指定Nginx进程的用户组
--with-compat																								#启动Nginx动态模块兼容性
--with-file-aio																							#启动Nginx aio使处理效率、处理大量IO性能大大提高
--with-threads																							#启动Nginx的多线程模块(根据CPU核数来启动,单核没必要启动)
--with-http_addition_module																	#启动Nginx的追加模块
--with-http_auth_request_module															#启动Nginx的认证模块
--with-http_dav_module																			#启动Nginx的上传下载模块
--with-http_flv_module																			#启动Nginx的播放视频模块
--with-http_gunzip_module																		#启动Nginx的压缩模块
--with-http_gzip_static_module															#启动Nginx的压缩模块
--with-http_mp4_module															        #启动Nginx的多媒体模块
--with-http_random_index_module											        #启动Nginx的随机主页模块
--with-http_realip_module											              #启动Nginx的用户真实IP模块
--with-http_secure_link_module											        #启动Nginx的安全连接模块
--with-http_slice_module											              #启动Nginx的中文文档模块
--with-http_ssl_module											                #启动Nginx的安全模块
--with-http_stub_status_module											        #启动Nginx的访问状态模块
--with-http_sub_module											                #启动Nginx的替换网站响应模块
--with-http_v2_module												                #启动Nginx的http v2模块
--with-mail																									#启动Nginx的邮件模块
--with-mail_ssl_module																			#启动Nginx的邮件安全模块
--with-stream																								#启动Nginx的负载均衡模块
--with-stream_realip_module																	#启动Nginx的负载均衡真实IP模块
--with-stream_ssl_module																		#启动Nginx的负载均衡安全模块
--with-stream_ssl_preread_module														#启动Nginx的负载均衡预读取模块
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong		#CPU优化参数
--param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC'												#CPU优化参数
--with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'																											#CPU优化参数

简单访问

查看IP地址

ip addr

浏览器访问IP

如果访问IP地址无法访问,需要检查是否服务器开启了防火墙,如开启需要关闭

systemctl status firewalld
systemctl stop firewalld
systemctl disable firewalld

注意:安装没有错误的前提下,如果扔无法访问Nginx,绝大部分情况是没有开放防火墙上的Nginx端口,简单处理方式即关闭防火墙。

访问展示

image.png

Nginx文件

yum安装文件路径

目录及文件

rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d																							#Nginx的子配置文件目录
/etc/nginx/conf.d/default.conf																#Nginx的默认子配置文件
/etc/nginx/fastcgi_params
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf																					#Nginx的主配置文件
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.25.3
/usr/share/doc/nginx-1.25.3/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html																						#Nginx的项目默认路径
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx																									#Nginx的默认日志路径

源码安装文件路径

所有目录

ll /usr/local/nginx
total 4
drwx------. 2 nginx root    6 Jan  4 01:49 client_body_temp
drwxr-xr-x. 2 root  root 4096 Jan  4 01:43 conf								#Nginx配置文件路径
drwx------. 2 nginx root    6 Jan  4 01:49 fastcgi_temp
drwxr-xr-x. 2 root  root   40 Jan  4 01:43 html								#Nginx项目默认路径
drwxr-xr-x. 2 root  root   58 Jan  4 01:49 logs								#Nginx默认日志路径
drwx------. 2 nginx root    6 Jan  4 01:49 proxy_temp
drwxr-xr-x. 2 root  root   19 Jan  4 01:43 sbin								#Nginx进程路径
drwx------. 2 nginx root    6 Jan  4 01:49 scgi_temp
drwx------. 2 nginx root    6 Jan  4 01:49 uwsgi_temp

关键文件

/usr/local/nginx/conf/nginx.conf					#Nginx配置文件
/usr/local/nginx/conf/nginx.conf.default	#Nginx配置文件模板
/usr/local/nginx/logs/access.log					#Nginx访问日志
/usr/local/nginx/logs/error.log						#Nginx错误日志

配置文件详解

Nginx配置文件三大模块

  1. 核心模块(CoreModule):进程数等配置;
  2. 事件驱动模块(EventsModule):工作模式等配置;
  3. http内核模块(HttpCoreModule):文档程序类型、配置文件等配置;

配置文件

主配置文件

user  nginx;																																		#全局设置,指定Nginx的启动用户
worker_processes  auto;																													#全局设置,指定Nginx的启动进程个数

error_log  /var/log/nginx/error.log notice;																			#全局设置,指定Nginx的错误日志存放路径
pid        /var/run/nginx.pid;																									#全局设置,指定Nginx的进程号存放路径


events {
  worker_connections  1024;																											#事件设置,指定Nginx的每个worker进程的最大连接数
}


http {
  include       /etc/nginx/mime.types;																					#HTTP设置,指定Nginx包含的媒体访问类型文件
  default_type  application/octet-stream;																				#HTTP设置,指定Nginx的流处理方式,默认为字节流处理方式

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '			#HTTP设置,指定Nginx的日志的记录格式
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  /var/log/nginx/access.log  main;																	#HTTP设置,指定Nginx的日志路径及使用的日志格式

  sendfile        on;																														#HTTP设置,加速Nginx访问
  #tcp_nopush     on;																														#HTTP设置,优化Nginx访问

  keepalive_timeout  65;																												#HTTP设置,指定Nginx的保持连接时长

  #gzip  on;																																		#HTTP设置,指定Nginx的gzip压缩

  include /etc/nginx/conf.d/*.conf;																							#HTTP设置,指定Nginx的子配置文件路径
}

子配置文件

server {
    listen       80;																								#网站配置,设置网站的Nginx监听端口
    server_name  localhost;																					#网站配置,设置网站的Nginx监听域名

  	#charset koi8-r;																								#网站配置,设置网站的字符集,默认使用UTF-8
    #access_log  /var/log/nginx/host.access.log  main;							#网站配置,设置网站访问日志的路径及日志的记录格式

    location / {
        root   /usr/share/nginx/html;																#网站网页配置,指定网站的根目录路径
        index  index.html index.htm;                                #网站网页配置,指定网站默认主页的文件名称
    }

    #error_page  404              /404.html;												#网站配置,指定网站的404错误页面

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;												#网站配置,指定网站的500系列的错误页面的显示内容
    location = /50x.html {
        root   /usr/share/nginx/html;																#网站网页配置,指定网站的500系列错误页面存放路径
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

日志文件详解

日志格式解释

  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;	

log_format:声明日志格式;
main:定义这个日志格式的名称;
$remote_addr:远程地址,记录客户端IP地址;
r e m o t e u s e r :远程用户,记录客户端访问用户名(有身份验证的前提下记录); [ remote_user:远程用户,记录客户端访问用户名(有身份验证的前提下记录); [ remoteuser:远程用户,记录客户端访问用户名(有身份验证的前提下记录);[time_local]:本地时间,服务器的自身时间(客户端访问时间);
“$request”:请求,记录请求的方式、请求的URL和请求的HTTP协议;
$status:请求状态码,记录请求的状态码;
b o d y b y t e s s e n t :发送给客户端的字节数,不包括响应头的大小; " body_bytes_sent:发送给客户端的字节数,不包括响应头的大小; " bodybytessent:发送给客户端的字节数,不包括响应头的大小;"http_referer":记录从哪个页面链接过来的访问(如果直接访问过来的则记录“-”);
h t t p u s e r a g e n t " :记录客户端浏览器相关信息; " http_user_agent":记录客户端浏览器相关信息; " httpuseragent":记录客户端浏览器相关信息;"http_x_forwarded_for”:记录代理IP
$request_length:记录请求的长度(包含请求行、请求头、请求正文);
$request_time:记录请求处理的时间,单位秒,精度是毫秒;
$time_iso8601:ISO8601标准格式下的本地时间;
$bytes_sent:记录发送给客户端的总字节数;
$msec:记录日志写入时间,单位秒,精度是毫秒;
$http_x_real_ip:记录真实客户端的ip,windows客户端ip;
$remote_addr:当无代理时候,是直接真实客户端的ip;
-:在日志中有两种情况,一表示占位符(如果没有记录使用占位符表示),二表示分隔符(没有特殊含义);

访问日志文件

192.169.1.101 - - [05/Jan/2024:23:45:59 +0800] "GET / HTTP/1.1" 200 17 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0" "-"

$remote_addr --> 192.169.1.101
r e m o t e u s e r − − > − [ remote_user --> - [ remoteuser>[time_local] --> [05/Jan/2024:23:19:56 +0800]
“$request” --> “GET / HTTP/1.1”
$status --> 200
b o d y b y t e s s e n t − − > 17 " body_bytes_sent --> 17 " bodybytessent>17"http_referer" --> “-”
h t t p u s e r a g e n t " − − > " M o z i l l a / 5.0 ( W i n d o w s N T 10.0 ; W i n 64 ; x 64 ; r v : 121.0 ) G e c k o / 20100101 F i r e f o x / 121.0 " " http_user_agent" --> "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0" " httpuseragent">"Mozilla/5.0(WindowsNT10.0;Win64;x64;rv:121.0)Gecko/20100101Firefox/121.0""http_x_forwarded_for” --> “-”

错误日志文件

  • 日志格式
error_log logs/error.log error;
  • 日志解释
  1. error_log:是记录错误日志的关键字,不能任意修改;
  2. logs/error.log:是记录错误日志的路径及文件名;
  3. error:指定错误日志记录的级别;
  4. 默认使用error级别,常见级别有:debug,info,notice,wam,error,crit,alert,emerg;
  5. 注意:级别越高记录的信息越少,一般常用的三个级别:wam,error,crit;
  6. 注意:不要配置info等低级别,会带来巨大的磁盘I/O消耗;
2024/01/06 00:43:35 [error] 15794#15794: *8 open() "/usr/share/nginx/html/adb" failed (2: No such file or directory), client: 192.169.1.101, server: localhost, request: "GET /adb HTTP/1.1", host: "192.169.1.133"

日志缓存

日志缓存可以配置在http/server/location下

http {
  open_log_file_cache max=1000 inactive=20s min_uses=3 valid=1m;
  ......
  server {
    ......
  }
}
  1. 默认情况下open_log_file_cache是关闭的,即open_log_file_cache off;
  2. max=1000:指定日志文件的FD,最大的缓存数量为1000;
  3. inactive=20s min_uses=3:在20秒内小于3次访问的FD,就会清理掉;
  4. valid=1m:检查周期为1分钟;
  5. 总结:缓存多个1000个,到了极限每分钟开始清除掉,20秒内小于3次的文件FD;
  6. 生成环境下不建议开启,因为会占用内存资源;

日志切割轮转

日志轮转切割可以使用linux的自带logrotate工具

  • 日志切割文件
cat /etc/logrotate.d/nginx

/var/log/nginx/*.log {
        daily													#每天轮转一次
        missingok											#日志丢失不提示
        rotate 52											#日志文件备份保留52份
        compress											#压缩日志文件,默认后缀.gz
        delaycompress									#延迟压缩
        notifempty										#空文件,不轮转
        create 640 nginx adm					#日志轮转后创建一个新文件,并授权
        size 10M											#日志文件大小超过10M时,启动日志轮转
        sharedscripts									#日志轮转后执行的脚本,开始标识
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid` #重启nginx
                fi
        endscript											#日志轮转后执行的脚本,结束标识
}
  • 测试日志轮转
logrotate -vf /etc/logrotate.d/nginx

日志分析

  1. 统计2023年9月5日,这一天内的PV量
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | wc -l
grep '05/Sep/2023:08' /var/log/nginx/access_zzx_log.log | wc -l		#(8点-9点直接的PV量)
  1. 统计2023年9月5日,这一天内的访问最多的10个IP
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{ips[$1]++}END{for(i in ips){print "IP地址:"i,"数量:"ips[i]}}' | sort -k2 -rn | head -n 10
  1. 统计2023年9月5日,这一天内的访问大于100次的IP
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{ips[$1]++}END{for(i in ips){if(ips[i]>100){print "IP地址:"i,"数量:"ips[i]}}}'
  1. 统计2023年9月5日,这一天内的访问最多的10个页面
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{urls[$7]++}END{for(i in urls){print "URL地址:"urls[i],"数量:"i}}' | sort -k1 -rn | head -n 10
  1. 统计2023年9月5日,这一天内的每个URL访问内容总量大小
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{urls[$7]++;size[$7]+=$10}END{for(i in urls){print "URL地址:"urls[i],"大小:"size[i]}}'
  1. 统计2023年9月5日,这一天内的每个IP访问状态码数量
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{ip_code[$1" "$9]++}END{for(i in ip_code){print "IP地址和状态码:"i,"数量:"ip_code[i]}}'
  1. 统计2023年9月5日,这一天内的每个IP访问状态码为404及出现次数
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{if($9="404"){ip_code[$1" "$9]++}}END{for(i in ip_code){print "IP地址和状态码:"i,"数量:"ip_code[i]}}'
  1. 统计2023年9月5日,这一天8:30-9:30时间段每个IP出现404状态码的数量
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '$4>="[05/Sep/2023:08:30:00" && $4<="[05/Sep/2023:09:00:00"{if($9="404"){ip_code[$1" "$9]++}}END{for(i in ip_code){print i,ip_code[i]}}'
  1. 统计2023年9月5日,这一天内的各种状态码数量
grep '05/Sep/2023' /var/log/nginx/access_zzx_log.log | awk '{code[$9]++}END{for(i in code){print i,code[i]}}'
  1. 统计前一分钟的PV量
date=$(date -d '-1 minute' +%Y:%H:%M); awk -v date=$date '$0 ~ date{i++}END{print i}' /var/log/nginx/access_zzx_log.log
  • 15
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值