nginx的常用模块配置详解,nginx的核心块使用,nginx http块使用,nginx location块使用

nginx的常用模块配置详解,nginx的核心块使用,nginx http块使用,nginx location块使用

1、编译安装nginx,搭建后台web转发环境

1.1 全部设备最小化安装centos7,初始化配置

cd /etc/yum.repos.d/
yum install -y wget
wget http://mirrors.aliyun.com/repo/Centos-7.repo
wget http://mirrors.aliyun.com/repo/epel-7.repo
mv CentOS-Base.repo CentOS-Base.repo.bak
yum clean all
yum makecache
systemctl stop firewalld
systemctl disable firewalld
sed -i 's/SELINUX=enforcing$/SELINUX=disabled/g' /etc/selinux/config
setenforce 0

1.2 2个web服务器配置
LAMP编译看这里:LAMP编译

vi /etc/hosts         修改hosts
192.168.116.130 test.nginx.web.io
192.168.116.131 test1.web1.http.io
192.168.116.132 test2.web2.http.io

yum install -y gcc expat-devel pcre-devel openssl-devel 安装依赖包
cd /root  在目录下载文件
wget http://archive.apache.org/dist/httpd/httpd-2.4.46.tar.gz --no-check-certificate
wget https://dlcdn.apache.org/apr/apr-util-1.6.1.tar.gz --no-check-certificate
wget https://dlcdn.apache.org/apr/apr-1.7.0.tar.gz --no-check-certificate
mkdir /httpd   创建安装目录
#编译apr
cd /root   切回目录
tar xf apr-1.7.0.tar.gz
cd apr-1.7.0
sed -ri 's@\$RM "\$cfgfile"@\# \$RM "\$cfgfile"@g' configure 
./configure --prefix=/httpd/apr

make && make install

#编译apr-tuils
cd /root   切回目录
tar xf apr-util-1.6.1.tar.gz 
cd apr-util-1.6.1
./configure --prefix=/httpd/apr-util --with-apr=/httpd/apr/

make && make install

#编译httpd
cd /root   切回目录
tar xf httpd-2.4.46.tar.gz 
cd httpd-2.4.46
./configure --prefix=/httpd \
--enable-so \
--enable-ssl \
--enable-cgi \
--enable-rewrite \
--with-zlib \
--with-pcre \
--with-apr=/httpd/apr/ \
--with-apr-util=/httpd/apr-util/ \
--enable-modules=most \
--enable-mpms-shared=all \
--with-mpm=event

make && make install

#配置httpd
useradd -s /sbin/nologin -r apache   创建账户
cd /httpd/conf/
sed -ri -e 's/User daemon/User apache/g'  -e 's/Group daemon/Group apache/g' httpd.conf   修改运行账户
echo "PATH=/httpd/bin:$PATH" >/etc/profile.d/httpd.sh  创建变量
source /etc/profile.d/httpd.sh

vi /usr/lib/systemd/system/httpd.service  创建httpd的service

[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)
[Service]
Type=forking
ExecStart=/httpd/bin/apachectl start
ExecReload=/httpd/bin/apachectl graceful
ExecStop=/httpd/bin/apachectl stop
KillSignal=SIGCONT
PrivateTmp=true
[Install]
WantedBy=multi-user.target

systemctl daemon-reload
chown apache.apache -R /httpd/
systemctl start httpd
systemctl enable httpd

编译安装php
yum -y install  libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel 
cd /root
wget https://www.php.net/distributions/php-7.4.19.tar.gz
tar xf php-7.4.19.tar.gz -C /usr/local/
cd /usr/local/php-7.4.19/

./configure \
--prefix=/php74 \
--enable-mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-openssl   \
--with-zlib \
--with-config-file-path=/etc \
--with-config-file-scan-dir=/etc/php.d \
--enable-mbstring \
--enable-xml \
--enable-sockets \
--enable-fpm \
--enable-maintainer-zts \
--disable-fileinfo

make  && make install

在安装目录/usr/local/php-7.4.19/下,不要切回/root
cp php.ini-production /etc/php.ini
cp sapi/fpm/php-fpm.service /usr/lib/systemd/system/  复制service
echo 'PATH=/php74/bin:$PATH' >/etc/profile.d/php.sh
source /etc/profile.d/php.sh
mv /php74/etc/php-fpm.conf.default /php74/etc/php-fpm.conf
mv /php74/etc/php-fpm.d/www.conf.default /php74/etc/php-fpm.d/www.conf

vi /php74/etc/php-fpm.d/www.conf   修改启动用户,把nobody改为apache
user = apache
group = apache


chown apache.apache -R /php74/
systemctl daemon-reload
systemctl start php-fpm
systemctl enable php-fpm
 
对httpd配置,让php文件的访问转发到9000端口
mkdir /httpd/conf.d/   创建子配置目录

vi /httpd/conf/httpd.conf

<IfModule dir_module>
    DirectoryIndex index.php index.html  #添加主页文件
</IfModule>
ServerName 127.0.0.1:80  #设置域名解析
#把#删了,开启模块支持
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#文件底部添加
AddType application/x-httpd-php .php
ProxyRequests Off
IncludeOptional /httpd/conf.d/*.conf

添加httpd的子配置文件,连接php
vi /httpd/conf.d/php.conf

<virtualhost *:80>
documentroot /httpd/htdocs
<directory /httpd/htdocs>
require all granted
</directory>
ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9000/httpd/htdocs/$1
</virtualhost>

上面配置都一样,下面创建2个web的网站文件
web1网站文件配置

添加index.html 文件
echo 192.168.116.131-test1.web1.http.io >/httpd/htdocs/index.html

vi /httpd/htdocs/index.php   添加php文件
<?php
phpinfo();
?>

systemctl restart httpd php-fpm  重启,使配置生效

web2网站文件配置

添加index.html 文件
echo 192.168.116.132-test2.web2.http.io >/httpd/htdocs/index.html

vi /httpd/htdocs/index.php   添加php文件
<?php
phpinfo();
?>

systemctl restart httpd php-fpm  重启,使配置生效

1.3 nginx(192.168.116.130)配置

编译安装nginx:

vi /etc/hosts       修改hosts
192.168.116.130 test.nginx.web.io
192.168.116.131 test1.web1.http.io
192.168.116.132 test2.web2.http.io

wget http://nginx.org/download/nginx-1.18.0.tar.gz
yum install -y gcc pcre-devel openssl-devel zlib-devel     安装依赖包
tar xf nginx-1.18.0.tar.gz 
cd nginx-1.18.0
useradd -r -s /sbin/nologin nginx    设置nginx账户
编译安装
./configure --prefix=/nginx \
--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 && make install
echo 'PATH=/nginx/sbin:$PATH' >/etc/profile.d/nginx.sh
source /etc/profile.d/nginx.sh

mkdir /nginx/run
vi /nginx/conf/nginx.conf
pid        /nginx/run/nginx.pid;          修改PID这行

chown -R nginx.nginx /nginx/

配置service
vi /usr/lib/systemd/system/nginx.service

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/nginx/run/nginx.pid
ExecStart=/nginx/sbin/nginx -c /nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target

systemctl daemon-reload  加载service文件
systemctl enable nginx
systemctl start nginx

测试nginx服务器和httpd是否正常运行

curl -I http://192.168.116.130
curl http://192.168.116.131/index.html
curl http://192.168.116.132/index.html
curl -I http://test.nginx.web.io
curl -I  http://test1.web1.http.io/index.php
curl -I http://test2.web2.http.io/index.php

在这里插入图片描述
在这里插入图片描述

2、nginx的模块使用

nginx模块说明:nginx模块说明

版块布局:
全局块一般只包括一个http块
每个http块可以包括多个server块
每个server块可以包括多个location块
在这里插入图片描述

2.1 nginx-Core functionality 核心功能常用配置

官网文档:nginx-Core functionality
文件配置地方:主要在主配置文件配置,是全局配置。

2.1.1 error_log 错误日志配置

配置模板:

Syntax:	error_log file [level];           #配置模板
Default:	
error_log logs/error.log error;           #配置示例
Context:	main, http, mail, stream, server, location  #使用模块范围

错误日志内容输出级别:debug, info, notice, warn, error, crit, alert, or emerg.(从左到右,从轻到重)
默认级别:error

在nginx配置测试,编译安装的nginx,会在安装目录下生成2个日志文件

ll /nginx/logs/     可以看到error.log 文件
vi /nginx/conf/nginx.conf            设置错误日志级别,一般在全局块中配置,可以在server块配置

error_log  logs/error.log  error;

nginx -t                              测试配置文件语法
nginx -s reload                       不重启加载nginx配置

在这里插入图片描述
在这里插入图片描述
测试错误日志是否正常工作

vi /nginx/conf/nginx.conf     修改文件配置

error_log  logs/error.log  error   #这里不添加逗号,制造错误

systemctl restart nginx   重启nginx会有报错
tail /nginx/logs/error.log  可以看到报错的地方,证明错误日志工作正常

在这里插入图片描述

2.1.2 include 子配置文件目录

配置模板

Syntax:	include file | mask;
Default:	—
Context:	any

因为主配置文件比较特殊,一般对后台web配置都分开配置,这样即使后台web子配置文件配错,也不会影响整个nginx。
配置nginx

mkdir /nginx/conf.d
chown -R nginx.nginx /nginx/conf.d/

vi /nginx/conf/nginx.conf    一般都是在http块配置

http {
    include /nginx/conf.d/*.conf
}

nginx -t         测试语法
nginx -s reload  加载配置

在这里插入图片描述

2.1.3 user 进程运行用户或组配置

配置模板:

Syntax:	user user [group];
Default:	
user nobody nobody;            #设置运行进程账户属主属组
Context:	main               #只能设置在main模块,也就是主配置文件上方

修改nginx

vi /nginx/conf/nginx.conf   全局块中配置

user  root;             #设置nginx运行账户为root,一般不建议配置root

systemctl restart nginx
ps -ef | grep nginx       可以看到进程原本是nginx账户,后面改成root账户

在这里插入图片描述

2.1.4 worker_connections连接数配置

配置模板

Syntax:	worker_connections number;
Default:	
worker_connections 512;
Context:	events                  在events环境下使用

配置nginx

vi /nginx/conf/nginx.conf    全局块中配置

events {
    #单个work进程打开的连接数限制,需要worker_processes的个数*worker_connections个数这样才能算出nginx总连接数(并发量)
    #一般还要和系统内核优化ulimit -n 102400和worker_rlimit_nofile参数 配合使用
    worker_connections  1024;  
}

测试并发,在客户端配置

yum install -y httpd-tools             安装压测工具
ulimit -n 102400                       修改系统最大打开文件个数限制
一直使用命令压测nginx服务器
while true;do ab -c 5000 -n 10000 http://192.168.116.130/;sleep 0.5;done

nginx服务器查看错误

tail /nginx/logs/error.log         可以看到nginx服务器出现错误

Too many open files                这个就是代表nginx服务器处理不了这么多请求了

在这里插入图片描述

2.1.5 worker_processes对worker进程个数配置

配置模板

Syntax:	worker_processes number | auto;
Default:	
worker_processes 1;
Context:	main         #全局配置,主配置

配置nginx,手动指定worker进程数

grep 'physical id' /proc/cpuinfo | sort -u  一般有多少个真实的CPU就创建多少个worker进程
vi /nginx/conf/nginx.conf    全局块中配置

worker_processes  2;      #一般指定为CPU个数

ps -ef | grep nginx       查看原本只有一个worker进程
nginx -s reload

ps -ef | grep nginx       配置文件生效后,可以看到有2个worker进程

在这里插入图片描述
配置nginx,自动设置worker进程数

grep 'processor' /proc/cpuinfo | sort -u | wc -l   查看线程数
vi /nginx/conf/nginx.conf      修改配置文件

worker_processes  auto;        #设置为自动,让nginx自动创建worker进程

nginx -s reload                重新加载配置
ps -ef | grep nginx            可以看到nginx默认是根据线程数创建worker进程

在这里插入图片描述

2.1.6 worker_cpu_affinity指定CPU跟worker进程绑定

配置模板

这里的0001和0010就是二进制的表现方式,其中0001代表第一个CPU,0010代表第二个,以此类推。

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000

默认nginx的worker进程会在CPU的线程数之间来回切换

grep 'processor' /proc/cpuinfo | sort -u | wc -l   查看线程数
vi /nginx/conf/nginx.conf     全局块中配置,只设置worker进程个数,不设置CPU绑定

worker_processes  2;

在另外一个终端实时查看,第3列就是CPU的线程数,因为是4线程,所以在worker进程会在CPU0线程到CPU3线程之间
watch -n.5 'ps axo comm,pid,psr,cmd | grep nginx '

在这里插入图片描述
指定CPU和worker进程绑定

vi /nginx/conf/nginx.conf      修改配置

worker_processes  2;            指定创建2个worker进程
worker_cpu_affinity 0001;       指定绑定第一个CPU

nginx -s reload                 重新加载配置
可以看到2个worker进程都是在0号CPU创建,而且不会切换到1号CPU
watch -n.5 'ps axo comm,pid,psr,cmd | grep nginx '

在这里插入图片描述

2.1.7 worker_rlimit_nofile最大打开文件限制

配置模板

Syntax:	worker_rlimit_nofile number;
Default:	—
Context:	main                 全局配置

配置nginx

vi /nginx/conf/nginx.conf               全局块中配置

#一般还要和系统内核优化ulimit -n 102400配合使用
#worker_processes的个数*worker_connections个数的总数不能大于这个
#所有worker进程能打开的文件数量上限
worker_rlimit_nofile 102400;
   
nginx -s reload

在这里插入图片描述

2.1.8 worker_priority进程nice优先级配置

配置模板
NICE:在LINUX系统中,Nice值的范围从-20到+19(不同系统的值范围是不一样的),正值表示低优先级,负值表示高优先级。NICE值越低,进程可能获得的 CPU时间就越多,值为0则表示不会调整该进程的优先级。

Syntax:	worker_priority number;
Default:	
worker_priority 0;
Context:	main         全局配置

nginx配置

vi /nginx/conf/nginx.conf   全局块中配置

worker_priority -5;

nginx -s reload
ps axo cmd,pid,ni |grep nginx   查看NICE值变成-5,优先级变高了

在这里插入图片描述

2.1.9 daemon是否前台运行

配置模板
nginx的进程默认是以守护进程(后台进程)启动,也就是daemon on。

Syntax:	daemon on | off;
Default:	
daemon on;
Context:	main

配置nginx

systemctl stop nginx        关闭nginx服务
ps -ef |grep nginx          可以看到没有进程

vi /nginx/conf/nginx.conf   全局块中配置,修改为前台运行

daemon off;                  #一般只作为容器配置使用

/nginx/sbin/nginx -c /nginx/conf/nginx.conf  前台运行nginx
在另外一个终端查看
ps -ef |grep nginx         可以看到nginx启动

在这里插入图片描述
在这里插入图片描述

2.1.10 进程PID文件配置

配置模板

Syntax:	pid file;
Default:	
pid logs/nginx.pid;
Context:	main

配置nginx

vi /nginx/conf/nginx.conf      全局块中配置

pid        /nginx/run/nginx.pid;  #指定PID文件,需要在nginx对这个目录有权限才能创建

systemctl start nginx
cat /nginx/run/nginx.pid     查看master进程的ID号
ps -ef |grep nginx           查看进程

在这里插入图片描述

2.1.11 accept_mutex 唤醒worker进程功能

配置模板
原理:

  • 当设置为on时,客户端访问nginx服务器时,指定一个worker进程接收请求,不会去唤醒其他worker进程。
  • 当设置为off时,客户端访问nginx服务器时,如果有多个worker进程,那么多个worker进程会抢夺这个请求进行回复,这种行为称为惊群效应。

使用方式:

  1. 当访问量较小或者是短连接时,建议开启这个功能
  2. 当访问量大或者是长连接时,建议关闭。

注意:在nginx的1.11.3版本之前都是on状态,后面新的版本默认都是off。

Syntax:	accept_mutex on | off;
Default:	
accept_mutex off;
Context:	events

配置nginx

vi /nginx/conf/nginx.conf      全局块中配置

events {
    accept_mutex on;
}

nginx -s reload

在这里插入图片描述

2.2 http配置块

2.2.1 ngx_http_core_module 全局核心配置

文档:nginx-http

  1. server_tokens 关闭nginx版本显示
    配置模板
Syntax:	server_tokens on | off | build | string;
Default:	
server_tokens on;
Context:	http, server, location

正常不关闭会显示nginx版本号,这样如果这个版本有漏洞更容易被入侵。

curl -I http://192.168.116.130

在这里插入图片描述
配置nginx

http块主要包括不同的server块,上面在http块定义了子目录,所以直接在/nginx/conf.d配置即可。
vi /nginx/conf.d/s1.conf    

server {
        listen 80;
        server_name test.nginx.web.io;
        server_tokens off;
        location / {
            root /nginx/html;
            index index.html;
        }
   }

nginx -s reload
再次访问网站可以看到没有显示版本号了
curl -I http://192.168.116.130

在这里插入图片描述

  1. error_page 错误页面配置
    配置模板
error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

配置方式:

创建2个错误界面
echo error-404 >/nginx/html/404.html
echo error-50x >/nginx/html/50x.html 

vi /nginx/conf/nginx.conf   必须配置在server模块下面,而且这个server要有监听端口,要不然不会返回界面

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        #实际生效就下面4行
        error_page 404 /404.html;
        location = /404.html {
            root /nginx/html;
        }
        location / {
            root /nginx/html;
            index index.html;
        }
}

nginx -s reload

curl -I http://192.168.116.130/dasdsa  访问一个不存在界面,可以看到返回码404

可以看到做好的404错误界面
curl  http://192.168.116.130/dasdsa

在这里插入图片描述
将404错误重写成500错误,证明500界面能够运行

vi /nginx/conf/nginx.conf   必须配置在server模块下面,而且这个server要有监听端口,要不然不会返回界面

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        error_page 404 =500 /50x.html;
        location = /50x.html {
            root /nginx/html;
        }
        location / {
            root /nginx/html;
            index index.html;
        }
}

nginx -s reload

curl -I http://192.168.116.130/dasdsa  可以看到返回码为500,界面也是50x的网页
curl  http://192.168.116.130/dasdsa

在这里插入图片描述

  1. keepalive_requests

客户端和服务器的一个保持活动连接提供服务的最大请求数。
配置模板

Syntax:	keepalive_requests number;
Default:	
keepalive_requests 1000;
Context:	http, server, location
This directive appeared in version 0.8.0.

keepalive_time
限制通过一个保持活动连接可以处理请求的最长时间。也就是开启一个连接后,多少时间后必须关闭这个连接。

注意:这个参数只能在nginx 1.19.10以上版本使用。
配置模板

Syntax:	keepalive_time time;
Default:	
keepalive_time 1h;
Context:	http, server, location

keepalive_timeout 配置模板
客户端和服务器之间连接的超时时间,也就是客户端在连接成功后,在这个时间内没有向服务器发出新的请求。这个时间一般低于上面keepalive_time的时间。默认时间是65秒。
配置模板

Syntax:	keepalive_timeout timeout [header_timeout];
Default:	
keepalive_timeout 75s;
Context:	http, server, location

配置方式:
Context: http, server, location 这个意思是代表在这3个版块下都可以配置。

vi /nginx/conf/nginx.conf      一般在http块配置,对全部server生效

    keepalive_time 1h;
    keepalive_requests 1000;
    keepalive_timeout  65s;

在这里插入图片描述

  1. limit_rate:网站下载速度限制

配置模板

Syntax:	limit_rate rate;
Default:	
limit_rate 0;
Context:	http, server, location, if in location

配置方式

vi /nginx/conf/nginx.conf   一般在http块配置,对全部server生效

http {
   limit_rate 1024k;
}

在这里插入图片描述

2.2.2 ngx_http_access_module 限制访问IP或网段模块

配置模板

location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

配置nginx

vi /nginx/conf/nginx.conf   将主配置文件的重复内容注释掉,要不然会冲突
http {
    include /nginx/conf.d/*.conf;  #添加子配置文件路径
    server {
       # listen       80;          #添加#号注销主配置文件网站
        #server_name  localhost;   #添加#号注销主配置文件网站
       #下面全部添加#号注销主配置文件网站
       # location / {
       #     deny 192.168.116.131;
       #     root   html;
       #     index  index.html index.htm;
       # }
}

vi /nginx/conf.d/s1.conf  在子配置文件下创建网站

server {
        listen 80;                         #设置网站访问端口
        server_name test.nginx.web.io;     #设置网站域名
        #定义网站访问根目录、访问策略、网站主页文件
        location / {
            deny 192.168.116.131; #这个就是限制IP或者IP段访问网站方式,可以添加#暂时关闭
            root   html;
            index  index.html index.htm;
        }
}

nginx -t
nginx -s reload

在这里插入图片描述

在192.168.116.131 访问测试

可以看到第一次访问返回码是200,证明访问网站成功
第二次访问返回403,代表没权限访问网站。
curl -I http://192.168.116.130

在这里插入图片描述

2.2.3 ngx_http_auth_basic_module 限制网站登录模块

配置模板

location / {
    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}

配置nginx

yum install -y httpd-tools       安装账户密码工具

创建2个账户
htpasswd  -bc /nginx/conf/.htpasswd aa test1234

#第二个账户开始不用加-c参数,要不然会重置文件
htpasswd  -b /nginx/conf/.htpasswd bb test1234
cat /nginx/conf/.htpasswd

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        location / {
            #定义弹窗内容,有些浏览器不会显示
            auth_basic    "auth login";
            #定义账户密码认证文件路径
            auth_basic_user_file  /nginx/conf/.htpasswd;
            root   html;
            index  index.html index.htm;
        }
}

nginx -t 
nginx -s reload

在这里插入图片描述
用浏览器访问网站,可以看到要求输入账户密码

在这里插入图片描述
在这里插入图片描述

2.2.4 ngx_http_log_module 网页访问日志

配置模板
客户端每次访问服务器,服务器都会记录访问的客户端信息,通过对客户端访问的来源IP,访问的资源等信息进行统计并且优化,从而让网站更受欢迎。

官网文档:nginx-access-log

可以根据自己的需要采集客户端的信息
log_format compression '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log compression buffer=32k;
参数解析
$remote_addr              存放客户端公网IP
$remote_user              网站登录账户(网站开启验证才会显示)
$time_local               客户端访问网站时间
$request                  显示访问的方法
$status $body_bytes_sent  显示主页表头
$http_referer             显示网页返回代码
$http_user_agent          显示请求的链接数量
$http_x_forwarded_for     显示代理转发地址
$server_name:$server_port 显示访问的浏览器和版本

配置nginx

vi /nginx/conf/nginx.conf   查看默认配置,增加自己定义的记录日志的内容

#必须在http{}模块配置需要采集的日志信息
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  logs/access.log  main;
   #定义日志的采集格式,名字为nginx_s1_log
   log_format  nginx_s1_log  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '$server_name:$server_port';
}

vi /nginx/conf.d/s1.conf   在子配置文件调用日志格式

server {
        listen 80;
        server_name test.nginx.web.io;
        #定义网页访问日志路径和日志格式名字
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root html;
            index index.html;
        }
}

tail /nginx/logs/access.log    查看老的日志没有记录访问域名和端口
ls /nginx/logs/                查看目录下也没有access-s1.log

nginx -s reload                加载配置
ls /nginx/logs/                查看目录下就多了access-s1.log 
tail /nginx/logs/access-s1.log 查看日志多了域名和端口
tail /nginx/logs/access.log    老的日志没有记录新定义的内容

在这里插入图片描述

2.2.5 ngx_http_gzip_module 网页压缩模块

配置模板
当客户访问网站时,用户访问图片多或者其他资源多的网页需要加载的时间会变长,当启用这个功能后,网页传输速度加快,这样让用户对网站的体验也会更好。

gzip            on;
gzip_min_length 1000;
gzip_proxied    expired no-cache no-store private auth;
gzip_types      text/plain application/xml;

配置nginx测试

将nginx主页内容加大,要不然不会启动压缩机制

tail -n 200 /var/log/messages >/nginx/html/index.html
tail -n 200 /var/log/messages >>/nginx/html/index.html
tail -n 200 /var/log/messages >>/nginx/html/index.html

tail /nginx/logs/access-s1.log
可以看到网页字节为55521

在这里插入图片描述
压缩后

vi /nginx/conf.d/s1.conf    增加压缩网页配置

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
        gzip  on;                #开启压缩
        gzip_comp_level 5;       #设置压缩级别,最高为9,最低为1
        gzip_min_length 1k;      #文件达到多少k进行压缩
        gzip_types text/plain application/javascript application/x-javascript text/css
        application/xml text/javascript application/x-httpd-php  image/gif image/png;   #设置被压缩的文件格式
            root html;
            index index.html;
        }
}

nginx -s reload                     服务器重新加载配置  
需要先把浏览器清除缓存,选择全部清除,然后重新打开浏览器,然后访问nginx网页。

tail /nginx/logs/access-s1.log      查看日志
200 55521       可以看到网页返回码都是200,说明没使用到缓存
200 3886        字节变成3886,证明网页变压缩了

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.2.6 ngx_http_proxy_module 反向代理模块

配置模板

location / {
    proxy_pass       http://localhost:8000;
    proxy_set_header Host      $host;
    proxy_set_header X-Real-IP $remote_addr;
}
  1. 配置nginx反向代理
vi /nginx/conf.d/s1.conf   配置反向代理

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            proxy_pass http://192.168.116.131; #设置后台web的网站IP或者域名
            index index.html;
        }
}

nginx -s reload        加载配置
访问nginx的IP
http://192.168.116.130
可以看到返回的是web1的网站信息,证明反向代理成功

在这里插入图片描述

在这里插入图片描述

  1. 反向代理将真实IP转发到后台web
    在后台web1查看上面的访问日志,可以看到nginx的IP是192.168.116.130,但是看不到真实的客户端访问IP
tail /httpd/logs/access_log 

在这里插入图片描述
修改nginx反向代理配置,让客户端IP信息发给web1

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            proxy_pass http://192.168.116.131;
            #定义转发客户端的IP到后台web,名字叫X-Real-IP
            proxy_set_header X-Real-IP $remote_addr;
            index index.html;
        }
}

修改web1的配置

vi /httpd/conf/httpd.conf

#找到这个日志定义,增加%{X-Real-IP}i,这个是接收nginx传过来的客户端IP,对应上面定义的名字
 LogFormat "%{X-Real-IP}i %h %l %u %t \"%r\" %>s %b" common

CustomLog "logs/access_log" common  #注意这个才是记录日志的文件

systemctl restart httpd

在这里插入图片描述
再次访问网站,测试web1是否有客户端IP的日志
在web1查看日志

tail /httpd/logs/access_log   可以看到客户端的IP

在这里插入图片描述

  1. nginx服务器缓存配置
yum install  -y tree 安装工具
vi /nginx/conf/nginx.conf   修改主配置文件,定义缓存

http {
#定义缓存目录和键名testcache,2:2:2是缓存目录结构
#单个缓存为128M,过期时间为180秒,缓存目录最大值为5G
    proxy_cache_path /nginx/proxycache   levels=2:2:2  keys_zone=testcache:128m inactive=180s  max_size=5g;
}

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            proxy_pass http://192.168.116.131;
            proxy_set_header X-Real-IP $remote_addr;
            #定义匹配上面定义的缓存键
            proxy_cache testcache;
            proxy_cache_key $request_uri;
            #定义指定的状态码缓存10分钟
            proxy_cache_valid 200 302 301 10m;
            #定义除了上面状态码其他状态码缓存时间
            proxy_cache_valid any 1m;
            index index.html;
        }
}

tree /nginx/proxycache/            查看缓存目录
查看缓存的内容
tail /nginx/proxycache/d9/c7/0c/6666cd76f96956469e7be39d750cc7d9 

在这里插入图片描述

在这里插入图片描述

2.2.7 ngx_http_fastcgi_module(网页动态数据处理模块)

配置模板
这个模块主要是将对客户端对动态网页的访问进行分开反向代理,减少服务器的压力。

location / {
    fastcgi_pass  localhost:9000;
    fastcgi_index index.php;

    fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
    fastcgi_param QUERY_STRING    $query_string;
    fastcgi_param REQUEST_METHOD  $request_method;
    fastcgi_param CONTENT_TYPE    $content_type;
    fastcgi_param CONTENT_LENGTH  $content_length;
}
  1. 单机配置lnp 架构,通过不同目录进行动静分离
    按照上面的web安装步骤,在nginx服务器上安装php
    配置nginx
vi /nginx/html/php/index.php         制作动态php网页

<?php
phpinfo();
?>

vi /nginx/conf.d/s1.conf          修改配置文件

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        #静态网页访问/目录,也就是/nginx/html目录。
        location / {
            root html;
            index index.html;
        }
        #动态网页访问/nginx/html/php
        location ~\.php$ {
            root /nginx/html/php;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
}

在其他设备访问测试动静分离
curl -I http://192.168.116.130/index.html   访问静态网页
curl -I http://192.168.116.130/index.php    访问动态网页,可以看到php版本

在这里插入图片描述

  1. 反向代理加动静分离,通过不同服务器进行动静分离
对web2的php监控端口进行修改
vi /php74/etc/php-fpm.d/www.conf      修改php配置

#修改php程序监听地址
listen = 192.168.116.132:9000
#修改客户端允许访问的IP
listen.allowed_clients = 192.168.116.130

systemctl restart php-fpm   重启配置


在nginx服务器配置
vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        #静态网页数据转发到web1
        location / {
            proxy_pass http://192.168.116.131;
        }
        #动态php网页转发到web2
        location ~\.php$ {
            fastcgi_pass   192.168.116.132:9000;
            fastcgi_index  index.php;
            #注意:/httpd/htdocs/这个目录是web2服务器的真机目录,不是nginx服务器的目录
            fastcgi_param  SCRIPT_FILENAME /httpd/htdocs/$fastcgi_script_name;
            include        fastcgi_params;
        }
}


curl http://192.168.116.130/index.html     可以看到静态网页为web1的服务器
curl -I http://192.168.116.130/index.php   动态网页为web2

在这里插入图片描述

  1. 缓存配置
    nginx服务器配置缓存
vi /nginx/conf/nginx.conf   修改主配置文件
#在这个http板块添加缓存定义
http {
#定义缓存目录/nginx/fcgicache,缓存等级,缓存键fcache
fastcgi_cache_path /nginx/fcgicache levels=2:1 keys_zone=fcache:10m max_size=2g;
}

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            proxy_pass http://192.168.116.131;
        }
        location ~\.php$ {
            fastcgi_pass   192.168.116.132:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME /httpd/htdocs/$fastcgi_script_name;
            include        fastcgi_params;
            #定义缓存限制,注意匹配键fcache
            fastcgi_cache fcache;
            fastcgi_cache_key $request_uri;
            fastcgi_cache_valid 200 302 10m;
            fastcgi_cache_valid 301     1h;
            fastcgi_cache_valid any     1m;
        }
}

tree /nginx/fcgicache/    在目录下可以看到缓存生成

在这里插入图片描述

2.2.8 ngx_http_ssl_module(http转为https模块)

https证书理解文档:https证书
配置模板

    server {
        listen              443 ssl;
        keepalive_timeout   70;

        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
        ssl_certificate     /usr/local/nginx/conf/cert.pem;
        ssl_certificate_key /usr/local/nginx/conf/cert.key;
        ssl_session_cache   shared:SSL:10m;
        ssl_session_timeout 10m;
    }

配置nginx

vi https.sh         通过脚本生成证书

#!/bin/bash
#生成CA,CA生成证书

#第一步,设置CA的国家和域名,网站证书国家和省份,城市一般和CA一致。
CA_SUBJECT="/O=BJ/CN=ca.web.io"

#第二步,设置nginx证书的国家CN,省份BJ,城市BJ,公司名test.nginx,域名test.nginx.web.io
SUBJECT="/C=CN/ST=BJ/L=BJ/O=test.nginx/CN=test.nginx.web.io"

#设置密码的长度
KEY_SIZE=2048 #此值不能使用1024
#设置CA的证书有效期
CA_EXPIRE=202002

#设置颁发客户端证书有效期
EXPIRE=365

#第三步,设置客户端文件名
FILE=test.nginx.web.io
#设置证书编号
SERIAL=34

#CA生成私钥,自己给自己颁发证书
openssl req  -x509 -newkey rsa:${KEY_SIZE} -subj $CA_SUBJECT -keyout cakey.pem -nodes -days $CA_EXPIRE -out cacert.pem

#第一个证书
#生成私钥和证书申请
openssl req -newkey rsa:${KEY_SIZE} -nodes -keyout ${FILE}.key  -subj $SUBJECT -out ${FILE}.csr
#颁发证书
openssl x509 -req -in ${FILE}.csr  -CA cacert.pem  -CAkey cakey.pem  -set_serial $SERIAL  -days $EXPIRE -out ${FILE}.crt
chmod 600 *.key

ls          查看证书信息在当前目录下生成
mkdir /nginx/ssl  创建证书目录

nginx的证书的信息是要合并起来的,就是这2个文件合并起来,nginx的在前,CA在后
cat test.nginx.web.io.crt cacert.pem >/nginx/ssl/test.nginx.web.io.crt
cp test.nginx.web.io.key /nginx/ssl/  钥匙也要放到目录下
ll /nginx/ssl/

在这里插入图片描述
在这里插入图片描述

nginx配置https的信息

vi /nginx/conf.d/s1.conf    配置ssl信息

server {
        listen 80;
        listen 443 ssl;  #https监听端口
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        #设置证书目录
        ssl_certificate /nginx/ssl/test.nginx.web.io.crt;
        #设置钥匙目录
        ssl_certificate_key /nginx/ssl/test.nginx.web.io.key;
        #设置会话缓存过期时间
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        location / {
            root html;
            index index.html;
        }
}

nginx -s reload
浏览器打开
因为是自己做的证书,所以不会被浏览器认可。
https://192.168.116.130  可以看到网站访问成功,使用的端口是443

在这里插入图片描述
在这里插入图片描述

2.2.9 ngx_http_rewrite_module (重定向模块)

官网文档:ngx_http_rewrite_module
实现方式:通过定义不同的规则,当客户端访问网页时,通过定义的规则,返回不同的界面给客户端。
配置模板

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}

if ($request_method = POST) {
    return 405;
}

if ($slow) {
    limit_rate 10k;
}

if ($invalid_referer) {
    return 403;
}
  1. 配置nginx不存在页面返回主页
修改主页方便访问
echo nginx-192.168.116.130 >/nginx/html/index.html 


vi /nginx/conf.d/s1.conf             配置网站

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        #当访问网页的界面不存在时,返回主页
        if ( !-e $request_filename ) {
              rewrite (.*) http://$host redirect;
        }
        location / {
            root html;
            index index.html;
        }
}

nginx -s reload
http://192.168.116.130/  正常访问网页没问题
http://192.168.116.130/aaabbb   访问不存在页面也是返回主页内容,但是返回代码为302,证明网页被重定向了。

在这里插入图片描述
在这里插入图片描述

  1. 配置目录重定向
    没有配置目录重定向前
mkdir /nginx/html/aa                    创建一个目录
echo nginx-aa >/nginx/html/aa/index.html  创建目录下网页

vi /nginx/conf.d/s1.conf     修改配置文件

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root html;
            index index.html;
        }
        location = /aa {
            root /nginx/html;
            index index.html;
        }
}

nginx -s reload

curl http://192.168.116.130/index.html     访问网页都正常
curl http://192.168.116.130/aa/index.html

因为没有break目录,所以报错404
curl http://192.168.116.130/break/

在这里插入图片描述
添加重定向后

vi /nginx/conf.d/s1.conf 
server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root html;
            index index.html;
        }
        location /break {
           rewrite ^/break/(.*) /aa/$1 break;
        }
        location = /aa {
            root /nginx/html;
            index index.html;
        }
}

nginx -s reload

curl http://192.168.116.130/index.html     访问网页都正常
curl http://192.168.116.130/aa/index.html

可以看到因为配置了重定向
所以http://192.168.116.130/break/就相当于http://192.168.116.130/aa/
只要aa目录下有什么文件,就会被访问到
curl http://192.168.116.130/break/

在这里插入图片描述

  1. http连接都重定向为https
    没配置前访问 http://192.168.116.130/
    可以看到没有自动从http跳为https
    在这里插入图片描述
    配置nginx

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        listen 443 ssl;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        ssl_certificate /nginx/ssl/test.nginx.web.io.crt;
        ssl_certificate_key /nginx/ssl/test.nginx.web.io.key;
        ssl_session_cache shared:sslcache:20m;
        ssl_session_timeout 10m;
        location / {
            if ( $scheme = http ) {
                     rewrite / https://$host permanent;
            }
            root html;
            index index.html;
        }
}

nginx -s reload
再次访问网页http://192.168.116.130/
可以看到自动跳转为https了
https://192.168.116.130/

在这里插入图片描述

2.2.10 ngx_http_stub_status_module(状态页模块)

配置模板

location = /basic_status {
    stub_status;
}

配置nginx,查看状态页返回内容

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root html;
            index index.html;
        }
        location /status {
            stub_status;
        }
}

nginx -s reload    

curl http://192.168.116.130/status/  查看nginx的访问信息
Active connections: 1           #当前处于活动状态的客户端连接数
server accepts                  #nginx累计接收客户端请求次数
handled                         #nginx累计处理客户端请求成功次数
requests                        #nginx累计客户端请求总数
Reading                         #服务器正在读取客户端请求表头的连接数量
Writing                         #服务器正在发送响应报文给客户端的连接数量
Waiting                         #当前等待请求的空闲客户端连接数

在这里插入图片描述

2.2.11 ngx_http_upstream_module(负载均衡模块)

负载均衡文档:http_upstream_module
算法文档:负载均衡算法演示
配置模板
功能:主要是通过对后台web服务器进行分组,将客户端的请求通过负载均衡的规则进行分配给web,减少单个后台web的访问压力。

http {
upstream backend {
    server backend1.example.com       weight=5;
    server backend2.example.com:8080;
    server unix:/tmp/backend3;

    server backup1.example.com:8080   backup;
    server backup2.example.com:8080   backup;
}

server {
    location / {
        proxy_pass http://backend;
    }
}
}
  1. 配置nginx平均回复请求
vi /nginx/conf/nginx.conf   主配置文件配置http模块,定义分组信息

http {
    upstream webs {
              server 192.168.116.131:80 fail_timeout=10s max_fails=3;
              server 192.168.116.132:80 fail_timeout=10s max_fails=3;
        }
}
webs              定义组名
fail_timeout=10s  表达多少秒后nginx测试web是否能正常工作
max_fails=3       表示当检测失败多少次就不将客户端请求发送给web

vi /nginx/conf.d/s1.conf   配置子配置文件

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            proxy_pass http://webs;  #将请求都转发到这个分组
            index index.html;
        }
}

nginx -s reload    加载配置

默认是一个web调度一次请求,所以web1和web2交换回复请求
curl http://192.168.116.130

在这里插入图片描述

  1. 加权回复请求
vi /nginx/conf/nginx.conf   主配置文件配置http模块,定义分组信息
http {
    upstream webs {
              server 192.168.116.131:80 weight=10 fail_timeout=10s max_fails=3;
              server 192.168.116.132:80 weight=5 fail_timeout=10s max_fails=3;
        }
}
子配置文件和上面一样
vi /nginx/conf.d/s1.conf   配置子配置文件

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            proxy_pass http://webs;  #将请求都转发到这个分组
            index index.html;
        }
}

nginx -s reload    加载配置
可以看到10次访问中,web1被访问次数较多
for i in {1..10};do curl http://192.168.116.130;done

在这里插入图片描述

2.2.12 ngx_http_rewrite_module (防盗链模块)

配置模板
原理:正常网站地址和内容都是通过搜索引擎或者宣传方式被客户端知晓。
假如有一个比较火的图片,只有A网站有版权发布,但是B网站为了提高自己网站访问量,将自己网站的某个图片链接到A网站的图片,访问B网站的用户只知道B网站,不知道A网站,B网站因为这个图片,访问量提高,导致损害A网站的权益。这个时候就需要做这个配置。

valid_referers none blocked server_names
               *.example.com example.* www.example.org/galleries/
               ~\.google\.;

if ($invalid_referer) {
    return 403;
}

在nginx服务器上放一张图片,让客户端访问

cp /usr/share/backgrounds/day.jpg /nginx/html/   复制系统图片到网站目录
vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
}

nginx -s reload
http://192.168.116.130/day.jpg  正常从nginx网站访问图片

在这里插入图片描述
配置一个盗链网站,将访问的图片指向nginx的图片

yum install -y nginx                    新的设备安装nginx网站
>/usr/share/nginx/html/index.html       清空老的网页
vi /usr/share/nginx/html/index.html     重新配置网页

<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>盗链</title>
</head>
<body>
<img src="http://192.168.116.130/day.jpg" >
<h1 style="color:red">192.168.116.133</h1>
<p><a href=http://192.168.116.133>test-192.168.116.133</a>欢迎你</p>
</body
</html>

systemctl start nginx   启动网站
http://192.168.116.133/  可以看到访问的是192.168.116.133,
但是在request URL可以看到真实的地址为192.168.116.130/day.jpg

在这里插入图片描述

在这里插入图片描述
nginx配置拒绝盗链

vi /nginx/conf.d/s1.conf               配置

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
            #设置允许转发过来的网址,一般设置允许搜索引擎转发请求过来
            valid_referers none blocked http://wwww.baidu.com/*;
            #当请求不是搜索引擎过来,返回403代码
            if ($invalid_referer) {
                 return 403;
            }
        }
}

nginx -s reload    加载配置

再次访问http://192.168.116.133/ 可以看到有转发,但是被拒绝了,返回403错误
在这里插入图片描述

2.2.13 ngx_http_autoindex_module(网站开启下载功能)

配置nginx

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
             root /nginx/html;
             index index.html;
        }
        location /images {
             autoindex on;              #开启下载功能
             autoindex_exact_size on;   #是否显示文件大小
             autoindex_localtime  on;   #是否使用当地时间
             limit_rate 1024k;          #设置下载速度
        }
}

nginx -s reload
http://192.168.116.130/images/   可以看到文件可以下载

在这里插入图片描述

2.3 location 配置块

2.3.1 alias 别名配置:当访问http://a.com/i的时候,实际访问为http://a.com/images/下面的内容

配置模板

location /i/ {
    alias /data/w3/images/;
}

配置nginx

mkdir /nginx/html/images    创建目录和网页
echo images-192.168.116.130 >/nginx/html/images/index.html

vi /nginx/conf.d/s1.conf  配置

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
        location /i {
            alias /nginx/html/images;
        }
}

nginx -s reload
ls /nginx/html
curl http://192.168.116.130/i/index.html
因为在/nginx/html/没有i目录或文件,正常情况下访问http://192.168.116.130/i/是没有东西显示的
设置了别名后,当访问http://192.168.116.130/i/实际就变成了http://192.168.116.130/images/
所以能被访问到网页。

在这里插入图片描述
在这里插入图片描述

2.3.2 location的匹配规则

文档:http-location

=  精准匹配,请求的内容和uri一一对应,区分大小写
^~ URI左半部分匹配,不区分大小写,如果最长匹配前缀位置具有“ ^~”修饰符,则不检查正则表达式。
~  区分大小写匹配
~* 不区分大小写进行匹配
注意:这里的不区分大小写指的是匹配的文件名字不区分大小写,但是linux的文件系统去查找时会区分大小写。
/  主目录定义,一般其他没匹配到就会去这里查找。

匹配优先级从高到低:=  ^~  ~/  ~* /
  1. = 和 ^~ 比较(= 大于 ^~)
mkdir /nginx/html/test1
mkdir /nginx/html/test2
echo /nginx/html/test1/test.html >/nginx/html/test1/test.html
echo /nginx/html/test2/test.html >/nginx/html/test2/test.html

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location = /test.html {
            root /nginx/html/test1;
            index index.html;
        }
        location ^~ /test.html {
            root /nginx/html/test2;
        }
}

nginx -s reload

可以看到是/nginx/html/test1,证明= 大于^~ 匹配
curl http://192.168.116.130/test.html

在这里插入图片描述

  1. = 和 ^~ 和 ~ 比较
mkdir /nginx/html/test3
echo /nginx/html/test3/test.html >/nginx/html/test3/test.html

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location = /test.html {
            root /nginx/html/test1;
            index index.html;
        }
        location ^~ /test.html {
            root /nginx/html/test2;
        }
        location ~ /test.html {
            root /nginx/html/test3;
        }
}


nginx -s reload

可以看到返回的是/nginx/html/test1的页面,证明= 是这3个中匹配度最高的
curl http://192.168.116.130/test.html

在这里插入图片描述
删除=,让^~ 和 ~ 比较

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ^~ /test.html {
            root /nginx/html/test2;
        }
        location ~ /test.html {
            root /nginx/html/test3;
        }
}

nginx -s reload

返回的页面是/nginx/html/test2目录下的网页,所以^~是要大于~
curl http://192.168.116.130/test.html

在这里插入图片描述

  1. = 和 ^~ 和 ~ 和 ~* 比较
mkdir /nginx/html/test4
echo /nginx/html/test4/test.html >/nginx/html/test4/test.html

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location = /test.html {
            root /nginx/html/test1;
            index index.html;
        }
        location ^~ /test.html {
            root /nginx/html/test2;
        }
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location ~* /test.html {
            root /nginx/html/test4;
        }
}

nginx -s reload

返回的页面是/nginx/html/test1目录下的网页,所以这4个中= 是最大的
curl http://192.168.116.130/test.html

在这里插入图片描述
删除=,比较其他3个

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ^~ /test.html {
            root /nginx/html/test2;
        }
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location ~* /test.html {
            root /nginx/html/test4;
        }
}

nginx -s reload

返回的页面是/nginx/html/test2目录下的网页,所以^~ 是大于~和~*
curl http://192.168.116.130/test.html

在这里插入图片描述
删除^~,比较 ~和 ~*

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location ~* /test.html {
            root /nginx/html/test4;
        }
}

nginx -s reload

返回的页面是/nginx/html/test3目录下的网页,所以~大于~*
curl http://192.168.116.130/test.html

在这里插入图片描述

  1. = 和 ^~ 和 ~ 和 ~* 和/ 比较
mkdir /nginx/html/test5
echo /nginx/html/test5/test.html >/nginx/html/test5/test.html

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location = /test.html {
            root /nginx/html/test1;
            index index.html;
        }
        location ^~ /test.html {
            root /nginx/html/test2;
        }
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location ~* /test.html {
            root /nginx/html/test4;
        }
        location / {
            root /nginx/html/test5;
        }
}

nginx -s reload

返回的页面是/nginx/html/test1目录下的网页,所以= 是匹配度最高的
curl http://192.168.116.130/test.html

在这里插入图片描述
删除=,测试其他匹配度

vi /nginx/conf.d/s1.conf
server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ^~ /test.html {
            root /nginx/html/test2;
        }
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location ~* /test.html {
            root /nginx/html/test4;
        }
        location / {
            root /nginx/html/test5;
        }
}

返回的页面是/nginx/html/test2目录下的网页,所以^~ 匹配度第二高
curl http://192.168.116.130/test.html

在这里插入图片描述
删除^~,测试其他匹配度

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location ~* /test.html {
            root /nginx/html/test4;
        }
        location / {
            root /nginx/html/test5;
        }
}

返回的页面是/nginx/html/test3目录下的网页,所以~ 匹配度第三高
curl http://192.168.116.130/test.html

在这里插入图片描述
删除~,测试匹配度

vi /nginx/conf.d/s1.conf 
server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ~* /test.html {
            root /nginx/html/test4;
        }
        location / {
            root /nginx/html/test5;
        }
}

返回的页面是/nginx/html/test4目录下的网页,所以~* 匹配度第四高
curl http://192.168.116.130/test.html

在这里插入图片描述

  1. 特殊匹配

在location /xxx和其他比较中

  • location = /xxx 大于location /xxx
  • location ~ /xxx 大于 location location /xxx
  • location ~* /xxx 大于 location location /xxx
  • location /xxx 大于 location /
  • location /xxx 大于 location location ^~ /xxx

location = /xxx 大于location /xxx

echo /nginx/html/test.html >/nginx/html/test.html

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location = /test.html {
            root /nginx/html/test1;
        }
        location /test.html {
            root /nginx/html/test5;
        }
}

nginx -s reload

返回的是/nginx/html/test1目录下的网页,所以location = /xxx 大于location /xxx
curl http://192.168.116.130/test.html

在这里插入图片描述
location /xxx 大于 location location ^~ /xxx

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ^~ /test {  #最左匹配,所以输入test
            root /nginx/html/test2;
        }
        location /test.html {
            root /nginx/html/test5;
        }
}

nginx -s reload
返回的是/nginx/html/test5目录下的网页,所以location /xxx 大于 location location ^~ /xxx
curl http://192.168.116.130/test.html

在这里插入图片描述
location ~ /xxx 大于 location location /xxx

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ~ /test.html {
            root /nginx/html/test3;
        }
        location /test.html {
            root /nginx/html/test5;
        }
}


nginx -s reload
返回的是/nginx/html/test3目录下的网页,所以location ~ /xxx 大于 location location  /xxx
curl http://192.168.116.130/test.html

在这里插入图片描述
location ~* /xxx 大于 location location /xxx

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location ~* /test.html {
            root /nginx/html/test4;
        }
        location /test.html {
            root /nginx/html/test5;
        }
}


nginx -s reload
返回的是/nginx/html/test4目录下的网页,所以location ~* /xxx 大于 location location  /xxx
curl http://192.168.116.130/test.html

在这里插入图片描述
location /xxx 大于 location /

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
        }
        location /test.html {
            root /nginx/html/test5;
        }
}

nginx -s reload

返回的是/nginx/html/test5目录下的网页,所以location /xxx 大于 location /
curl http://192.168.116.130/test.html

在这里插入图片描述

  1. location的正则表达式运用
    图片匹配
mkdir /nginx/html/images    创建目录

cd /usr/share/backgrounds
cp *.jpg /nginx/html/images/
cp *.png /nginx/html/images/

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
        location ~* \.(jpg|png)$ {
            root /nginx/html/images;
        }
}

nginx -s reload

可以看到主页就会去/nginx/html目录
curl -I http://192.168.116.130/

图片文件就会去/nginx/html/images目录
curl -I http://192.168.116.130/day.jpg
curl -I http://192.168.116.130/default.png

在这里插入图片描述

2.3.3 location和proxy_pass详解

  1. location目录配置问题
    错误配置
mkdir /nginx/html/aa
echo aa-192.168.116.130 >/nginx/html/aa/index.html

想要访问http://192.168.116.130/aa/index.html,但是配成下面
vi /nginx/conf.d/s1.conf   错误配置

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
        location /aa {
            root /nginx/html/aa;  #错误配置
        }
}

>/nginx/logs/error.log   清空错误日志
nginx -s reload


访问测试,查看日志得到错误位置

curl  http://192.168.116.130/index.html
curl  http://192.168.116.130/aa/index.html
tail /nginx/logs/error.log 

可以看到当访问http://192.168.116.130/aa/index.html,变成了去/nginx/html/aa/aa目录查找,因为/nginx/html/aa/没有再多一个aa目录了,所以查找不到
/nginx/html/aa/aa/index.html

在这里插入图片描述
在这里插入图片描述
正确配置:

vi /nginx/conf.d/s1.conf 

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
        location /aa {
            root /nginx/html;  #设置为这个,就会去/nginx/html加上上面的/aa目录下查找文件
        }
}

nginx -s reload
curl  http://192.168.116.130/index.html
curl  http://192.168.116.130/aa/index.html

在这里插入图片描述

  1. location和proxy_pass重复文件问题
    web1配置一个网站目录和网页
echo app-web1 >/httpd/htdocs/app.html
mkdir /httpd/htdocs/app
echo app-web1-192.168.116.131 >/httpd/htdocs/app/app.html

nginx配置

echo app-nginx >/nginx/html/app.html
mkdir /nginx/html/app
echo app-nginx-192.168.116.130 >/nginx/html/app/app.html

nginx没配置代理前

vi /nginx/conf.d/s1.conf 
server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
}

nginx -s reload

可以看到访问都是nginx目录下的文件
curl  http://192.168.116.130/app.html
curl  http://192.168.116.130/app/app.html

在这里插入图片描述
nginx配置代理后

vi /nginx/conf.d/s1.conf

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
        location /app {
            proxy_pass http://192.168.116.131;
        }
}
nginx -s reload

可以看到虽然nginx服务器的目录有相同的目录和文件
但是访问都是web1的目录下的文件
curl  http://192.168.116.130/app.html
curl  http://192.168.116.130/app/app.html

在这里插入图片描述

  1. location和proxy_pass的斜杠问题
错误配置1
vi /nginx/conf.d/s1.conf   以下其他部分省略,只保留location部分

server {
        listen 80;
        server_name test.nginx.web.io;
        access_log  logs/access-s1.log  nginx_s1_log;
        location / {
            root /nginx/html;
            index index.html;
        }
        location /app {
            proxy_pass http://192.168.116.131;
        }
}

错误配置2
        location /app/ {
            proxy_pass http://192.168.116.131;
        }
错误配置3
        location /app {
            proxy_pass http://192.168.116.131/app;
        }
错误配置4
        location /app {
            proxy_pass http://192.168.116.131/app/;
        }

错误配置5
        location /app/ {
            proxy_pass http://192.168.116.131/app/;
        }

nginx -s reload

curl  http://192.168.116.130/app/index.html
实际访问是http://192.168.116.131/app/index.html
这里的app是web1的目录,因为web1的app目录下没有index.html,所以文件没找到,报错404

curl  http://192.168.116.130/app/app.html
因为web1的app目录有app.html,所以访问web1的app目录下的app.html可以访问

在这里插入图片描述
错误配置6

        location /app/ {
            proxy_pass http://192.168.116.131/app;
        }
错误配置7
        location / {
            proxy_pass http://192.168.116.131/app;
        }
错误配置8
        location / {
            proxy_pass http://192.168.116.131/app/;
        }
        
这些情况会直接找不到文件
curl  http://192.168.116.130/app/index.html
curl  http://192.168.116.130/app/app.html

在这里插入图片描述
正确配置

正确配置1
location /app {
  proxy_pass http://192.168.116.131/;
}

正确配置2
        location /app/ {
            proxy_pass http://192.168.116.131/;
        }

实际访问为http://192.168.116.131//app  2个/会直接当成1个/
这里的app就相当于web1的/httpd/htdocs/目录

curl  http://192.168.116.130/app/index.html  实际就是把/app替换成了/httpd/htdocs/目录
curl  http://192.168.116.130/app/app.html
curl  http://192.168.116.130/app/app/app.html

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值