nginx
(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。
nginx
由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。
第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。
nginx
的特点是占有内存少,并发能力强,事实上nginx
的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx
网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。
nginx
是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:
nginx
由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。
nginx的模块从结构上分为核心模块、基础模块和第三方模块
用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大
nginx模块从功能上分为三类,分别是:
nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等
具体的指令,请参考nginx
的官方文档
nginx
的模块直接被编译进nginx
,因此属于静态编译方式。
启动nginx
后,nginx
的模块被自动加载,与Apache
不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。
在解析配置文件时,nginx
的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。
nginx
的进程架构:
启动nginx
时,会启动一个Master
进程,这个进程不处理任何客户端的请求,主要用来产生worker
线程,一个worker
线程用来处理n个request
。
下图展示了nginx
模块一次常规的HTTP请求和响应的过程
下图展示了基本的WEB服务请求步骤
(1)建立连接 — 接受一个客户端连接,或者如果不希望与这个客户端建立连接,就将其关闭。
(2)接收请求 — 从网络中读取一条 HTTP 请求报文。
(3)处理请求 — 对请求报文进行解释,并采取行动。
(4)访问资源 — 访问报文中指定的资源。
(5)构建响应 — 创建带有正确首部的 HTTP 响应报文。
(6)发送响应 — 将响应回送给客户端。
(7)记录事务处理过程 — 将与已完成事务有关的内容记录在一个日志文件中。
//关闭防火墙与SELINUX
[root@localhost ~]# systemctl disable --now firewalld
[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# setenforce 0
[root@localhost ~]# reboot
//创建系统用户nginx
[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx
//安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++
[root@localhost ~]# yum -y groups mark install 'Development Tools'
//创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx
//下载nginx
[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget http://nginx.org/download/nginx-1.20.1.tar.gz
--2021-10-23 21:45:53-- http://nginx.org/download/nginx-1.20.1.tar.gz
正在解析主机 nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
正在连接 nginx.org (nginx.org)|3.125.197.172|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1061461 (1.0M) [application/octet-stream]
正在保存至: “nginx-1.20.1.tar.gz”
100%[=============================================================================>] 1,061,461 26.2KB/s 用时 17s
2021-10-23 21:46:11 (61.7 KB/s) - 已保存 “nginx-1.20.1.tar.gz” [1061461/1061461])
//编译安装
[root@localhost src]# ls
debug kernels nginx-1.20.1.tar.gz
[root@localhost src]# tar xf nginx-1.20.1.tar.gz
[root@localhost src]# cd nginx-1.20.1
[root@localhost nginx-1.20.1]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@localhost nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
安装过程略....
//配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# . /etc/profile.d/nginx.sh
[root@localhost ~]# which nginx
/usr/local/nginx/sbin/nginx
//服务控制方式,使用nginx命令
-t //检查配置文件语法
-v //输出nginx的版本
-c //指定配置文件的路径
-s //发送服务控制信号,可选值有{stop|quit|reopen|reload}
-t
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
-v -V
[root@localhost ~]# nginx -v
nginx version: nginx/1.21.3
[root@localhost ~]# nginx -V
nginx version: nginx/1.21.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
-c
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# cp mime.types nginx.conf /opt/
[root@localhost conf]# nginx -s stop; nginx -c /opt/nginx.conf
[root@localhost conf]# ps -ef | grep nginx
root 6834 1 0 18:19 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx 6835 6834 0 18:19 ? 00:00:00 nginx: worker process
nginx 6836 6834 0 18:19 ? 00:00:00 nginx: worker process
root 7061 1494 0 18:20 pts/0 00:00:00 grep --color=auto nginx
[root@localhost conf]# nginx -s stop; nginx ##使用快捷键删除ctrl+w
[root@localhost conf]# ps -ef | grep nginx
root 7935 1 0 18:20 ? 00:00:00 nginx: master process nginx
nginx 7936 7935 0 18:20 ? 00:00:00 nginx: worker process
root 7983 1494 0 18:20 pts/0 00:00:00 grep --color=auto nginx
-s
[root@localhost ~]# nginx -s quit
[root@localhost ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
配置.service服务开机自启文件
[root@localhost ~]# cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/bin/kill -HUP
[Install]
WantedBy=multi-user.target
//重新加载
[root@localhost ~]# systemctl daemon-reload
//启动nginx
[root@localhost ~]# systemctl enable --now nginx
[root@localhost ~]# systemctl status nginx
● nginx.service - nginx
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 六 2021-10-23 22:17:06 CST; 2min 30s ago
Main PID: 41588 (nginx)
CGroup: /system.slice/nginx.service
├─41588 nginx: master process /usr/local/nginx/sbin/nginx
└─41589 nginx: worker process
10月 23 22:17:06 localhost.localdomain systemd[1]: Starting nginx...
10月 23 22:17:06 localhost.localdomain systemd[1]: Started nginx.
[root@localhost ~]# ss -antl
ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
主配置文件:/usr/local/nginx/conf/nginx.conf
nginx
常见的配置文件及其作用
配置文件 | 作用 |
---|---|
nginx.conf | nginx的基本配置文件 |
mime.types | MIME类型关联的扩展文件 |
fastcgi.conf | 与fastcgi相关的配置 |
proxy.conf | 与proxy相关的配置 |
sites.conf | 配置nginx提供的网站,包括虚拟主机 |
nginx.conf的内容分为以下几段:
配置指令:要以分号结尾,语法格式如下:
derective value1 [value2 ...];
支持使用变量:
set var_name value
daemon {on|off}; //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off}; //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别; //配置错误日志
error_log里的位置和级别能有以下可选项:
位置 | 级别 |
---|---|
file stderr syslog:server=address[,parameter=value] memory:size |
debug:若要使用debug级别,需要在编译nginx时使用–with-debug选项 info notice warn error crit alert emerg |
user USERNAME [GROUPNAME]; //指定运行worker进程的用户和组
pid /path/to/pid_file; //指定nginx守护进程的pid文件
worker_rlimit_nofile number; //设置所有worker进程最大可以打开的文件数,默认为1024
worker_rlimit_core size; //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可
//nginx安装过后配置文件中的user默认是nobody,但是配置文件中user参数是注释掉的,即使我们把注释去掉,默认user也不是nobody,是nginx
[root@localhost ~]# ps -ef |grep nginx
root 13317 1 0 23:17 ? 00:00:00 nginx: master process nginx
nginx 13318 13317 0 23:17 ? 00:00:00 nginx: worker process
nginx 13319 13317 0 23:17 ? 00:00:00 nginx: worker process
nginx 13320 13317 0 23:17 ? 00:00:00 nginx: worker process
root 13395 1488 0 23:17 pts/0 00:00:00 grep --color=auto nginx
[root@localhost ~]# cat /usr/local/nginx/conf/nginx.conf
user nginx nginx;
worker_processes 3;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
pid logs/nginx.pid; #取消注释
......
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
worker_rlimit_nofile 65535;
......
[root@localhost ~]# nginx -s reload
//增大系统允许打开的文件数,修改系统配置文件
[root@localhost ~]# vim /etc/security/limits.conf
[root@localhost ~]# tail -2 /etc/security/limits.conf
* soft nofile 65535 #末尾添加此行
* hard nofile 65535 #末尾添加此行
[root@localhost ~]# ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 14996
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 14996
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
//设置完成以后重开一个终端或者重启即可生效
[root@localhost ~]# ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 14996
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 65535
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 14996
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
worker_processes n; //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...; //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
0000 0001 //第一颗cpu核心
0000 0010 //第二颗cpu核心
0000 0100 //第三颗cpu核心
0000 1000 //第四颗cpu核心
0001 0000 //第五颗cpu核心
0010 0000 //第六颗cpu核心
0100 0000 //第七颗cpu核心
1000 0000 //第八颗cpu核心
timer_resolution interval; //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number; //指明worker进程的nice值
上下文切换
nice:其取值范围是-20至19,一共40个级别。这个值越小,表示进程”优先级”越高,而值越大“优先级”越低。
配置参数
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
worker_processes 2;
worker_cpu_affinity 0101 1010;
......
[root@localhost ~]# nginx -s stop;nginx
查看nginx运行在哪
使用命令top,输入L后输入nginx
看到nginx进程以后,点击f键
按q键退出,此时就可以看到进程所对应的核心数
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
worker_processes 2;
worker_cpu_affinity 0101 1010;
worker_rlimit_nofile 65535;
worker_priority -20; #修改优先级为-20
......
[root@localhost ~]# nginx -s stop;nginx
accept_mutex {off|on}; //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file; //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll]; //指明使用的事件模型,建议让nginx自行选择
worker_connections #; //每个进程能够接受的最大连接数
#以上四个参数,前三个一般配置时选择默认,但是第四个参数worker_connections是一定要配置的
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
user nginx nginx;
worker_processes 2;
worker_cpu_affinity 0101 1010;
worker_rlimit_nofile 65535;
worker_priority -20;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 20480; #最大连接数乘以进程数量除以2就是最大访问并发量300
}
keepalive_timeout number; //长连接的超时(在65s内没有任何操作)时长,默认为65s
keepalive_requests number; //在一个长连接上所能够允许请求的最大资源数(处理完成后在处理)
keepalive_disable [msie6|safari|none]; //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off; //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number; //读取http请求报文首部的超时时长
client_body_timeout number; //读取http请求报文body部分的超时时长
send_timeout number; //发送响应报文的超时时长
#网络连接我们用的做多的就是前两个(超时、最大资源数)
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
http {
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;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65; #默认
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
http {
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;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
keepalive_requests 1000;
LNMP:php要启用fpm模型
配置示例如下:
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000; //定义反向代理,此处的IP地址应该为PHP服务器的地址
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
http{…}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:
http { //协议级别
include mime.types;
default_type application/octet-stream;
keepalive_timeout 65;
gzip on;
upstream { //负载均衡配置
...
}
server { //服务器级别,每个server类似于httpd中的一个<VirtualHost>
listen 80;
server_name localhost;
location / { //请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
root html;
index index.html index.htm;
}
}
}
http{}段配置指令:
server {}:定义一个虚拟主机,示例如下:
server {
listen 8080; (域名可以给多个)
server_name www.hhr.com;
location / {
root html/test; (网站位置) or alias /var/www/html/;(别名一定要写绝对路径,就是把资源放到另外一个位置,当有人访问时,看见的路径是/根下面,其实我们已经放在了另一个位置,防止被攻击)
index index.html index.htm;
}
}
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html index.html
[root@localhost html]# mkdir test
[root@localhost html]# echo 'jjyy' > test/index.html
[root@localhost html]# nginx -s reload
[root@localhost html]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:8080 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
listen:指定监听的地址和端口
listen address[:port];
listen port;
server_name NAME [...];
后面可跟多个主机,名称可使用正则表达式或通配符
当有多个server时,匹配顺序如下:
*.idfsoft.com
mail.*
~ ^.*\.idfsoft\.com$
root path;
设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径
alias path;
用于location配置段,定义路径别名(加绝对路径
)
index file;
默认主页面
index index.php index.html;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
alias /var/www/html/;
index index.html index.htm;
}
[root@localhost ~]# mkdir /var/www/html -p
[root@localhost html]# mv /usr/local/nginx/html/test/ .
[root@localhost html]# ls
test
[root@localhost html]# cd test/
[root@localhost test]# ll
总用量 4
-rw-r--r--. 1 root root 5 10月 27 00:57 index.html #注意权限让所有人能访问
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
48 error_page 404 /404.html; #取消注释
......
[root@localhost ~]# vim /usr/local/nginx/html/404.html #创建自定义错误页面
[root@localhost ~]# cat /usr/local/nginx/html/404.html
zhe shi yi ge gong yi wangzhan!
[root@localhost ~]# nginx -s reload
error_page code [...] [=code] URI | @name` 根据http响应状态码来指明特用的错误页面,例如 `error_page 404 /404_customed.html
[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404.html
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
error_page 404 =200 /404.html
......
[root@localhost ~]# nginx -s reload
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; #访问日志
//log_format中每一段的含义
remote_addr:对应客户端的地址
remote_user:是请求客户端请求认证的用户名,如果没有开启认证模块的话是值为空。
time_local:表示nginx服务器时间
request:表示request请求头的行
status:表示response的返回状态
body_bytes_sent:表示从服务端返回给客户端的body数据大小
http_referer:表示请求的上一级页面
http_user_agent:表示agent信息
http_x_forwarded_for:会记录每一级请求中信息
//注意:此处可用变量为nginx各模块内建变量
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf #取消下列几行的注释
......
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;
......
[root@localhost ~]# nginx -s reload
[root@localhost ~]# curl 192.168.129.33 # 访问测试
1.获取老版本的编译参数-V
[root@localhost ~]# nginx -V
nginx version: nginx/1.21.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
2.获取新版本或新功能的软件包
下载地址 github.com
[root@localhost ~]# cd /usr/src/
[root@localhost src]# ls
debug echo-nginx-module-master.tar kernels nginx-1.21.3
[root@localhost src]# tar xf echo-nginx-module-master.tar
[root@localhost src]# ls
debug echo-nginx-module-master echo-nginx-module-master.tar kernels nginx-1.21.3
3.对新功能或新版本的软件包进行编译
[root@localhost src]# cd nginx-1.21.3/
[root@nginx nginx-1.21.3]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
[root@nginx nginx-1.21.3]# make
4.备份老程序
[root@localhost nginx-1.21.3]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 7069888 10月 27 23:55 objs/nginx
-rwxr-xr-x. 1 root root 6452216 10月 25 16:25 /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.21.3]# cp /usr/local/nginx/sbin/nginx /opt/
[root@localhost nginx-1.21.3]# ls /opt/
mime.types nginx nginx.conf
5.停掉老程序并用新程序使用老程序的配置文件进行启动
[root@localhost nginx-1.21.3]# nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.21.3]# ps -ef|grep nginx
root 62044 1487 0 00:00 pts/0 00:00:00 grep --color=auto nginx
6.检验功能,若无问题即用新程序替换老程序
[root@localhost nginx-1.21.3]# objs/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.21.3]# objs/nginx -s reload
7.测试
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
}
location /test {
echo "test";
}
[root@localhost nginx-1.21.3]# objs/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.21.3]# objs/nginx -s reload
[root@localhost ~]# curl http://192.168.129.33/test
test
[root@localhost nginx-1.21.3]# \cp objs/nginx /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.21.3]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 7069888 10月 27 23:55 objs/nginx
-rwxr-xr-x. 1 root root 7069888 10月 28 00:12 /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.21.3]# objs/nginx -s stop;nginx
[root@localhost nginx-1.21.3]# ps -ef | grep nginx
root 48446 1 0 00:50 ? 00:00:00 nginx: master process nginx
nginx 48447 48446 0 00:50 ? 00:00:00 nginx: worker process
root 48938 1494 0 00:50 pts/0 00:00:00 grep --color=auto nginx
location区段,通过指定模式来与客户端请求的URI相匹配
//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
//语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:
修饰符 | 功能 |
---|---|
= | 精确匹配 |
~ | 正则表达式模式匹配,区分大小写 |
~* | 正则表达式模式匹配,不区分大小写 |
^~ | 前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式 |
@ | 定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等 |
没有修饰符表示必须以指定模式开始,如:
[root@localhost local]# vim nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
}
location /test {
echo "test";
}
[root@localhost ~]# nginx -s reload
那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.129.33/test
test
[root@localhost ~]# curl http://192.168.129.33/test/
test
[root@localhost ~]# curl http://192.168.129.33/test?test
test
=:表示必须与指定的模式精确匹配,如:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /test { #匹配/test下的所有
echo "test";
}
location =/test {
echo "111";
}
[root@localhost ~]# nginx -s reload
那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.129.33/test
111
如下内容则无法匹配:
[root@localhost ~]# curl http://192.168.129.33/test/
test
[root@localhost ~]# curl http://192.168.129.33/test/hh
test
[root@localhost ~]# curl http://192.168.129.33/testtest
test
~:表示指定的正则表达式要区分大小写,如:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /test {
echo "test";
}
location ~ ^/test$ {
echo "大小写";
}
[root@localhost ~]# nginx -s reload
那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.129.33/test
大小写
如下内容则无法匹配:
[root@localhost ~]# curl http://192.168.129.33/test/
test
[root@localhost ~]# curl http://192.168.129.33/testkllk
test
~*:表示指定的正则表达式不区分大小写,如:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
location ~ ^/test$ {
echo "大小写";
}
[root@localhost ~]# nginx -s reload
那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.129.33/test
不分大小写
[root@localhost ~]# curl http://192.168.129.33/TEST
不分大小写
[root@localhost ~]# curl http://192.168.129.33/TEst
不分大小写
如下内容则无法匹配:
[root@localhost ~]# curl http://192.168.129.33/TEst/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.21.3</center>
</body>
</html>
[root@localhost ~]# curl http://192.168.129.33/testas
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.21.3</center>
</body>
</html>
~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /test {
echo "无";
}
location ~ ^/test$ {
echo "分大小写";
}
location ~* ^/test$ {
echo "不分大小写";
}
[root@localhost ~]# nginx -s reload
那么如下内容就可正确匹配:
[root@localhost ~]# curl http://192.168.129.33/test
分大小写
[root@localhost ~]# curl http://192.168.129.33/tesT
不分大小写
[root@localhost ~]# curl http://192.168.129.33/test/
无
[root@localhost ~]# curl http://192.168.129.33/test/asda
无
[root@localhost ~]# curl http://192.168.129.33/testasda
无
查找顺序和优先级:由高到底依次为
=
的精确匹配优先^~
修饰符的,开头匹配~
或~*
修饰符的,如果正则表达式与URI匹配优先级次序如下:
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( locatio
用于location段
allow:设定允许哪台或哪些主机访问,多个参数间则换行
deny:设定禁止哪台或哪些主机访问,多个参数间则换行
示例:
allow 192.168.1.1/32 ;
allow 192.168.2.1/32 ;
deny all;
示例:
[root@localhost ~]# mkdir /usr/local/nginx/html/test -p
[root@localhost ~]# cat > /usr/local/nginx/html/test/index.html >>EOF
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
EOF
[root@localhost ~]# nginx -s reload
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /test {
deny 192.168.129.1; ## 黑名单(除了自己谁都能访问)
root html;
index index.html;
}
.....
[root@localhost ~]# curl http://192.168.129.33/test/index.html
<html>
<head>
<title>test page</title>
</head>
<body>
<a href="http://www.baidu.com">baidu</a>
</body>
</html>
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
location / {
root html;
index index.html index.htm;
}
location /test {
allow 192.168.129.1; #白名单(除了自己谁都不能访问)
deny all;
root html;
index index.html;
}
.....
[root@localhost ~]# curl http://192.168.129.33/test/index.html
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.21.3</center>
</body>
</html>
auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"
user_auth_file内容格式为:
username:password
这里的密码为加密后的密码串,建议用htpasswd来创建此文件:
htpasswd -c -m /path/to/.user_auth_file USERNAME
示例:
#安装httpd-tools
[root@localhost ~]# yum -y install httpd-tools
[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass admin
New password:
Re-type new password:
Adding password for user admin
[root@localhost ~]# id admin
id: admin: no such user #虚拟用户
[root@localhost ~]# cat /usr/local/nginx/conf/.pass
admin:$apr1$VoP2WB3J$goBaTZ7d.vz9t4NBhIHVi/
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /test {
auth_basic "欢迎信息";
auth_basic_user_file ".pass"; #写入存放文件路径(如果文件在同级目录,可直接写)
root html;
index index.html;
}
[root@localhost ~]# nginx -s reload
生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中配置如下内容:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 443 ssl;
server_name www.idfsoft.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
示例:
//CA生成一对密钥
[root@localhost ~]# mkdir /etc/pki/CA
[root@localhost ~]# cd /etc/pki/CA/
[root@localhost CA]# mkdir private
[root@localhost CA]# umask 077;openssl genrsa -out private/cakey.pem 2048
Generating RSA private key, 2048 bit long modulus
..............+++
.+++
e is 65537 (0x10001)
//CA生成自签署证书
[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:rr
Organizational Unit Name (eg, section) []:rr
Common Name (eg, your name or your server's hostname) []:hh.example.com
Email Address []:1@1.com
//生成密钥
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial
[root@localhost CA]# cd /usr/local/nginx/
[root@localhost nginx]# ls
client_body_temp conf fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp
[root@localhost nginx]# mkdir ssl
[root@localhost nginx]# #(umask 077;openssl genrsa -out nginx.key 2048)
[root@localhost nginx]# cd ssl
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
......+++
.....+++
e is 65537 (0x10001)
//客户端生成证书签署请求
[root@localhost ssl]# pwd
/usr/local/nginx/ssl
[root@localhost ssl]# ls
nginx.key
[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:rr
Organizational Unit Name (eg, section) []:rr
Common Name (eg, your name or your server's hostname) []:hh.example.com
Email Address []:1@1.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
//CA签署客户端提交上来的证书
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 1 (0x1)
Validity
Not Before: Oct 27 18:55:29 2021 GMT
Not After : Oct 27 18:55:29 2022 GMT
Subject:
countryName = CN
stateOrProvinceName = HB
organizationName = rr
organizationalUnitName = rr
commonName = hh.example.com
emailAddress = 1@1.com
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
FD:98:15:D9:77:26:27:CE:38:4E:76:C5:77:95:98:40:CF:4D:59:C8
X509v3 Authority Key Identifier:
keyid:9D:7A:1A:6D:98:04:0F:27:F9:69:77:F2:CC:C5:1F:20:80:E0:65:AD
Certificate is to be certified until Oct 27 18:55:29 2022 GMT (365 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost ssl]# ls
nginx.crt nginx.csr nginx.key
[root@localhost ssl]# rm -f nginx.csr #删除掉
[root@localhost ssl]# ls
nginx.crt nginx.key
//修改nginx配置文件
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#取消104~121的注释
104 server {
105 listen 443 ssl;
106 server_name hh.example.com; #改成域名
107
108 ssl_certificate /usr/local/nginx/ssl/nginx.crt; #可以填写相对路径
109 ssl_certificate_key /usr/local/nginx/ssl/nginx.key;
110
111 ssl_session_cache shared:SSL:1m;
112 ssl_session_timeout 5m;
113
114 ssl_ciphers HIGH:!aNULL:!MD5;
115 ssl_prefer_server_ciphers on;
116
117 location / {
118 root html;
119 index index.html index.htm;
120 }
121 }
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 *:443 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
开启status:
location /status {
stub_status on;
allow 172.16.0.0/16;
deny all;
}
示例:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /status {
stub_status ;
allow 192.168.129.33;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
访问状态页面的方式:http://server_ip/status
注意
reading值大:
很多请求在等待接受 处理能力不够
writing值大 :
对端处理能力低、网络慢
waiting值大:
说明工作很闲 处理任务不饱和
waiting值越小越好:
工作饱和 只有几个人在等待,如果没有人等待表示工作不饱和很闲,实际中不会这么浪费 会近可能的给机器安排工作。
状态页面信息详解:
状态码 | 表示的意义 |
---|---|
Active connections 2 | 当前所有处于打开状态的连接数 |
accepts | 总共处理了多少个连接 |
handled | 成功创建多少握手 |
requests | 总共处理了多少个请求 |
Reading | nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数 |
Writing | nginx返回给客户端的Header信息数,表示请求已经接收完成, 且正处于处理请求或发送响应的过程中的连接数 |
Waiting | 开启keep-alive的情况下,这个值等于active - (reading + writing), 意思就是Nginx已处理完正在等候下一次请求指令的驻留连接 |
环境说明
主机名 | ip | 服务 | 系统 |
---|---|---|---|
localhost | 192.168.129.33 nginx zabbix_agent | centos7 | |
Server | 192.168.129.250 | zabbix_server | redhat8 |
准备工作
localhost 安装nginx、zabbix_agent服务
Server安装zabbix_server服务
详细步骤查看此文章
配置
//修改agent配置文件/usr/local/etc/zabbix_agentd.conf
[root@localhost zabbix-5.4.4]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1 #取消注释并修改值为1
Server=192.168.129.250
ServerActive=192.168.129.250 #服务端IP
Hostname=NGINX
//启动服务
[root@localhost zabbix-5.4.4]# zabbix_agentd
[root@localhost zabbix-5.4.4]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:10050 *:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 *:443 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
//编写的脚本
[root@localhost ~]# mkdir /scripts
[root@localhost ~]# vim /scripts/check_status.sh
#!/bin/bash
if [ `curl -s http://192.168.129.33/status|awk 'NR==4 {print $6}' ` -gt 30 ]
then
echo "1"
else
echo "0"
fi
[root@localhost ~]# chmod +x /scripts/check_status.sh
[root@localhost ~]# chown -R zabbix.zabbix /scripts/check_status.sh
[root@localhost ~]# ll
总用量 4
-rwxr-xr-x. 1 zabbix zabbix 127 10月 28 22:30 check_status.s
测试脚本
[root@localhost ~]# ./scripts/check_status.sh
0
配置zabbix配置文件
[root@localhost ~]# vim /usr/local/etc/zabbix_agentd.conf
写入以下:
UserParameter=check_status[*],/scripts/check_status.sh $1 #取消331行的注释并添加内容
[root@localhost ~]# pkill zabbix
[root@localhost ~]# zabbix_agentd
服务端测试
[root@Server ~]# zabbix_get -s 192.168.129.33 -k check_status #服务端测试
0
语法:rewrite regex replacement flag;
,如:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
如上例所示,replacement可以是某个路径,也可以是某个URL
常见的flag
flag | 作用 |
---|---|
last | 基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个 一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理 而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程 |
break | 中止Rewrite,不再继续匹配 一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求, 且不再会被当前location内的任何rewrite规则所检查 |
redirect | 以临时重定向的HTTP状态302返回新的URL |
permanent | 以永久重定向的HTTP状态301返回新的URL |
rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)
break 本条规则匹配完成即终止,不再匹配后面的任何规则
[root@localhost ~]# /usr/local/nginx/html/
[root@localhost html]# mkdir imgs
[root@localhost html]# ls
50x.html imgs index.html test
[root@localhost html]# ls images/
1.gif 2.webp
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ /imgs/$1 break;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ https://www.linuxprobe.com/wp-content/uploads/2020/05/2653e3c945f3ca8b91108ccf35b8aa81.jpg-wh_651x-s_3754039934.jpg break;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir imgs
[root@localhost html]# ls
404.html 50x.html imgs index.html
[root@localhost imgs]# ls
1.gif 2.webp
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ http://images.baidu.com/ redirect;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
last 本条规则匹配完成后,继续向下匹配新的location URI规则
break 本条规则匹配完成即终止,不再匹配后面的任何规则
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir imgs
[root@localhost html]# ls
404.html 50x.html imgs index.html
[root@localhost imgs]# ls
1.gif 2.webp
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ /imgs/$1 last;
}
location /imgs {
rewrite ^/imgs/(.*\.webp)$ http://images.baidu.com/ last;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
浏览器访问
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir imgs
[root@localhost html]# ls
404.html 50x.html imgs index.html
[root@localhost imgs]# ls
1.gif 2.webp
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ /imgs/$1 break;
}
location /imgs {
rewrite ^/imgs/(.*\.webp)$ http://images.baidu.com/ last;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
浏览器访问
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ /imgs/$1 redirect;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
浏览器访问
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
......
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /images {
rewrite ^/images/(.*\.webp)$ /imgs/$1 permanent;
}
#error_page 404 /404.html;
......
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# nginx -s reload
浏览器访问
nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:
标识符 | 意义 |
---|---|
^ | 必须以^后的实体开头 |
$ | 必须以$前的实体结尾 |
. | 匹配任意字符 |
[] | 匹配指定字符集内的任意字符 |
[^] | 匹配任何不包括在指定字符集内的任意字符串 |
| | 匹配 | 之前或之后的实体 |
() | 分组,组成一组用于匹配的实体,通常会有 | 来协助 |
捕获子表达式,可以捕获放在()之间的任何文本,比如:
^(hello|sir)$ //字符串为“hi sir”捕获的结果:$1=hi$2=sir
//这些被捕获的数据,在后面就可以当变量一样使用了
语法:if (condition) {...}
应用场景:
常见的condition
if ($http_user_agent ~ Firefox) {
rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
if ($http_user_agent ~ Chrome) {
rewrite ^(.*)$ /chrome/$1 break;
}
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referers none blocked www.idfsoft.com;
if ($invalid_referer) {
rewrite ^/ http://www.idfsoft.com/403.html;
}
}
静态资源:
可以理解为前端的固定页面,这里面包含HTML、CSS、JS、图片等等,不需要查数据库也不需要程序处理,直接就能够显示的页面,如果想修改内容则必须修改页面,但是访问效率相当高。
动态资源:
需要程序处理或者从数据库中读数据,能够根据不同的条件在页面显示不同的数据,内容更新不需要修改页面但是访问速度不及静态页面。
nginx
通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。
nginx
实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx
发布的路径去读取,而不需要从后台服务器获取了。
但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync
做服务端自动同步或者使用NFS
、MFS
分布式共享存储。
Http Proxy`模块,功能很多,最常用的是`proxy_pass`和`proxy_cache
如果要使用proxy_cache
,需要集成第三方的ngx_cache_purge
模块,用来清除指定的URL缓存。这个集成需要在安装nginx
的时候去做,如:
./configure --add-module=../ngx_cache_purge-1.0 ......
nginx
通过upstream
模块来实现简单的负载均衡,upstream
需要定义在http
段内
在upstream
段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:
upstream idfsoft.com {
ip_hash;
server 127.0.0.1:9080 weight=5;
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:1111;
}
注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。
定义好upstream
后,需要在server
段内添加如下内容:
server {
location / {
proxy_pass http://idfsoft.com;
}
}
环境说明
主机名 | IP | 服务 |
---|---|---|
nginx | 192.168.129.3 | nginx |
agent | 192.168.129.33 | nginx |
httpd | 192.168.129.133 | httpd |
注:nginx服务都是源码安装 、httpd为yum安装
准备工作
此文章有详细步骤:https://blog.csdn.net
每台主机开启服务,并关闭防火墙
修改配置
[root@agent ~]# vim /usr/local/nginx/conf/nginx.conf
......
#gzip on;
upstream webservers { #配置负载均衡
server 192.168.129.3;
server 192.168.129.133;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / { #配置反向代理
proxy_pass http://webservers;
}
#error_page 404 /404.html;
......
[root@agent ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@agent ~]# nginx -s reload
环境说明
主机名 | IP | 服务 |
---|---|---|
lnmp | 192.168.129.135 | lnmp架构 |
agent | 192.168.129.33 | nginx |
httpd | 192.168.153.139 | httpd |
准备工作
此文章有详细步骤:https://blog.csdn.net
开启服务
//lnmp主机
[root@lnmp ~]# nginx
[root@lnmp ~]# systemctl start php-fpm.service
[root@lnmp ~]# systemctl start mysqld.service
[root@lnmp ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:9000 0.0.0.0:*
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 80 *:3306 *:*
LISTEN 0 128 [::]:22 [::]:*
//httpd主机
[root@httpd ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 *:80 *:*
LISTEN 0 128 [::]:22 [::]:*
//agent主机
[root@agent ~]# nginx
nginx: [emerg] still could not bind()
[root@agent ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
修改agent主机配置文件
[root@agent ~]# vim /usr/local/nginx/conf/nginx.conf
......
#gzip on;
upstream static {
server 192.168.129.33; #httpd主机的ip
}
upstream dynamic {
server 192.168.129.135; #lnmp主机的ip
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://static; #访问静态资源会自动跳转到进行访问
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
location ~ \.php$ {
proxy_pass http://dynamic; #访问动态资源会自动跳转到进行访问
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
......
[root@agent ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@agent ~]#
[root@agent ~]# nginx -s reload
使用agent主机IP地址访问测试