企业高性能web服务器-Nginx

web服务基础介绍

Web服务是一种面向服务的架构(SOA)的技术,通过标准的Web协议(如HTTP、SOAP等)提供服务,旨在保证不同平台的应用服务可以互操作。它通常是由许多应用程序接口(API)所组成的,这些API通过网络(如互联网)的远程服务器端,执行客户所提交服务的请求。

web服务介绍

Apache工作原理

prefork模型

优点:稳定

缺点:不适合高并发

worker模型

优点:占有内存少,可以处理更多请求

缺点:

event模型

缺点:没有线程安全控制

网络I/O模型

1、阻塞型I/O

定义
阻塞型I/O是最常见的I/O模型。在这种模型中,当一个线程发起一个I/O操作请求后,该线程会阻塞(即暂停执行),直到操作完成。在这段时间内,该线程不能进行其他任务。

特点

  • 简单直接:程序逻辑简单,易于理解和实现。
  • 资源消耗:在I/O操作等待期间,线程处于空闲状态,资源利用率低。
  • 适用场景:适用于顺序访问、数据量较小的场景,如简单的文件读取操作。

2、非阻塞型I/O

定义
非阻塞型I/O是指程序在发送一个I/O请求后无需等待其响应,期间可以执行其他任务,从而提高程序运行的效率。

实现方式

  • 非阻塞调用:将I/O操作设置为立即响应,如果立即处理不了,就返回一个错误代码(如EWOULDBLOCK或EAGAIN)。
  • 轮询检查:程序需要不断地检查I/O操作的状态,直到操作完成。

特点

  • 提高效率:在I/O操作等待期间,程序可以执行其他任务。
  • CPU占用高:由于需要不断轮询检查I/O状态,可能会增加CPU的负担。
  • 适用场景:适用于需要处理多个I/O操作,且每个操作耗时较短的场景。

3、多路复用型I/O

定义
多路复用型I/O是指一个或少量线程(或进程)同时处理多个I/O操作。这种模型通过复用线程(或进程)来减少系统资源的消耗。

实现方式

  • 使用select/poll/epoll等系统调用:这些系统调用可以同时监测多个I/O操作的状态,当有I/O操作完成时,再通知相应的线程(或进程)进行处理。

特点

  • 资源利用高:通过复用线程(或进程)来减少系统资源的消耗。
  • 灵活性强:可以同时处理多个I/O操作,提高系统的并发处理能力。
  • 适用场景:适用于需要处理大量并发连接的网络服务器等场景。

4、信号驱动式I/O

定义
信号驱动式I/O是指进程预先告知内核,当某个描述符上发生特定事件时(如数据到达),内核使用信号通知相关进程。

实现方式

  • 设置信号处理器:进程通过调用sigaction等函数设置信号处理函数,当特定事件发生时,内核会发送信号给进程,进程通过信号处理函数来响应这些事件。

特点

  • 响应及时:当I/O事件发生时,内核会立即发送信号通知进程,进程可以迅速响应。
  • 复杂度较高:需要处理信号和信号处理函数的同步问题,以及信号处理函数与主程序之间的通信问题。
  • 适用场景:适用于需要快速响应I/O事件的场景,如实时数据处理系统等。

5、异步I/O

定义
异步I/O是一种支持数据传输完成前可以允许其他计算的I/O模型。在这种模型中,当程序发起一个I/O操作后,该操作由系统完全接管,程序可以继续执行其他任务。当I/O操作完成时,系统会以某种方式(如回调函数)通知程序。

特点

  • 非阻塞:程序在发起I/O操作后无需等待其完成,可以继续执行其他任务。
  • 高效性:系统负责I/O操作的全过程,减少了程序的等待时间。
  • 复杂度较高:需要处理回调函数的编写和调用等问题。
  • 适用场景:适用于需要处理大量I/O操作,且对性能要求较高的场景,如高性能数据库等。

Nginx-高性能的web服务端

Nginx 是一款高性能的开源Web服务器,同时也可以用作反向代理服务器和负载均衡器。本文将详细探讨Nginx的代理功能、负载均衡功能以及其它优点,提供配置示例、应用场景、注意事项以及完整的Nginx配置文件模板,以下是其主要优点:

  • 轻量级:Nginx是一款轻量级的服务器,占用较少的系统资源,适用于嵌入式设备和资源有限的环境。
  • 高性能:Nginx是一个事件驱动的Web服务器,具有出色的并发处理能力。它可以处理大量并发连接,而不会显著增加服务器负载。
  • 反向代理:Nginx可以用作反向代理服务器,将客户端请求转发到后端服务器,隐藏后端服务器的信息。这对于提高安全性和负载均衡至关重要。
  • 负载均衡:Nginx支持多种负载均衡算法,如轮询、加权轮询、IP哈希等,使您可以均衡分发流量到多个后端服务器,提高性能和可用性。
  • 高可用性:通过将Nginx配置为负载均衡器,可以实现故障转移和容错,确保即使某些后端服务器出现问题,仍然能够提供连续的服务。
  • 灵活配置:Nginx的配置文件采用简洁的文本格式,易于理解和修改,使管理员能够轻松自定义服务器行为。

Nginx 架构和安装

Nginx是一款高性能的HTTP和反向代理服务器,采用模块化、事件驱动和Master-Worker进程模型设计,能够高效地处理大量并发连接,提供静态文件服务、反向代理、负载均衡等功能,是构建高性能Web服务器和反向代理服务器的理想选择。

安装Nginx

源码编译

[root@nginx ~]# tar zxf nginx-1.24.0.tar.gz

进入解压目录

[root@nginx ~]# cd nginx-1.24.0/

[root@nginx nginx-1.24.0]# ls

auto     CHANGES.ru  configure  html     man     src

CHANGES  conf        contrib    LICENSE  README

指定要用的模块,检测需要的环境

./configure --prefix=/usr/local/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

#需要c语言编译

[root@nginx nginx-1.24.0]# yum install gcc -y

#下载pcre

[root@nginx nginx-1.24.0]# yum install pcre-devel.x86_64 -y

#下载openssl

[root@nginx nginx-1.24.0]# yum install openssl-devel.x86_64 -y

#下载zlib

[root@nginx nginx-1.24.0]# yum install zlib-devel.x86_64 -y

 

检测完成

[root@nginx nginx-1.24.0]# ls

auto     CHANGES.ru  configure  html     Makefile  objs    src

CHANGES  conf        contrib    LICENSE  man       README

 

编译

[root@nginx nginx-1.24.0]# make    #-j2--两核

拷贝到指定目录

[root@nginx nginx-1.24.0]# make install


[root@nginx sbin]# useradd -s /sbin/nologin -M nginx

[root@nginx sbin]# id nginx

uid=1001(nginx) gid=1001(nginx) groups=1001(nginx)

 

启动

[root@nginx ~]# cd /usr/local/nginx/sbin/

[root@nginx sbin]# ./nginx

[root@nginx sbin]# ps aux | grep nginx

root       44637  0.0  0.1   9868  2052 ?        Ss   12:29   0:00 nginx: master process ./nginx

nginx      44638  0.0  0.2  14200  5124 ?        S    12:29   0:00 nginx: worker process

root       44642  0.0  0.1 221664  2304 pts/0    S+   12:30   0:00 grep --color=auto nginx

 

删除

[root@nginx ~]# cd nginx-1.24.0/

[root@nginx nginx-1.24.0]# ls

auto     CHANGES.ru  configure  html     Makefile  objs    src

CHANGES  conf        contrib    LICENSE  man       README

 

[root@nginx nginx-1.24.0]# rm -rf /usr/local/nginx/

[root@nginx nginx-1.24.0]# make clean

 

关闭debug功能,减少内存

[root@nginx nginx-1.24.0]# vim auto/cc/gcc

# debug

#CFLAGS="$CFLAGS -g"        #把这一行注释

 

# DragonFly's gcc3 generates DWARF

#CFLAGS="$CFLAGS -g -gstabs"

 

if [ ".$CPP" = "." ]; then

    CPP="$CC -E"

fi

 

[root@nginx ~]# du -sh /usr/local/nginx/sbin/nginx

1.2M    /usr/local/nginx/sbin/nginx

 

 

[root@nginx nginx-1.24.0]# vim ~/.bash_profile

# .bash_profile

 

# Get the aliases and functions

if [ -f ~/.bashrc ]; then

        . ~/.bashrc

fi

 

# User specific environment and startup programs

export PATH=$PATH:/usr/local/nginx/sbin

 

[root@nginx ~]# source ~/.bash_profile

平滑升级

[root@nginx ~]# tar zxf echo-nginx-module-0.63.tar.gz

[root@nginx ~]# ls

anaconda-ks.cfg  echo-nginx-module-0.63         nginx-1.24.0.tar.gz  Templates

Desktop          echo-nginx-module-0.63.tar.gz  nginx-1.26.1.tar.gz  Videos

Documents        Music                          Pictures

Downloads        nginx-1.24.0                   Public

[root@nginx ~]# tar zxf nginx-1.26.1.tar.gz

[root@nginx ~]# ls

anaconda-ks.cfg  echo-nginx-module-0.63         nginx-1.24.0.tar.gz  Public

Desktop          echo-nginx-module-0.63.tar.gz  nginx-1.26.1         Templates

Documents        Music                          nginx-1.26.1.tar.gz  Videos

Downloads        nginx-1.24.0                   Pictures

[root@nginx ~]# cd nginx-1.26.1/

[root@nginx nginx-1.26.1]# ls

auto     CHANGES.ru  configure  html     man     src

CHANGES  conf        contrib    LICENSE  README





[root@nginx nginx-1.26.1]# ./configure --prefix=/usr/local/nginx --add-module=/root/echo-nginx-module-0.63 --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

 

[root@nginx nginx-1.26.1]# make    #make编译不install

[root@nginx nginx-1.26.1]# cd

[root@nginx ~]# cd /usr/local/nginx/sbin/

[root@nginx sbin]# ls

nginx  nginx.old

[root@nginx sbin]# cp nginx nginx.bak

覆盖

[root@nginx sbin]# \cp -f /roozt/nginx-1.26.1/objs/nginx /usr/local/nginx/sbin/nginx

[root@nginx sbin]# ps ax | grep nginx

[root@nginx sbin]# nginx

启动新版本

[root@nginx sbin]# kill -USR2 57949

回收旧版本

[root@nginx sbin]# kill -WINCH 57949

平滑回滚

[root@nginx sbin]# kill -HUP 57949

回收新版本

[root@nginx sbin]# kill -WINCH 58007

Nginx常用命令

以下是一些常见的Nginx命令,以及它们的用途:

1. 启动Nginx服务

./nginx

2. 查看Nginx版本号

nginx -v
或
nginx -V

3. 查看Nginx进程

ps aux | grep nginx

4. 检查Nginx配置文件是否正确

nginx -t

5. 指定检测特定Nginx配置文件

nginx -t -c /etc/nginx/nginx.conf

6. 指定Nginx配置文件启动Nginx服务器

nginx -c /etc/nginx/nginx.conf

7. 强行停止Nginx服务器

nginx -s stop

8. 优雅停止Nginx服务器

nginx -s quit

9. 重新加载Nginx配置文件

nginx -s reload

10. 显示Nginx帮助信息

nginx -h

Nginx核心配置

设置开机自启动

[root@nginx ~]# vim /lib/systemd/system/nginx.service

[Unit]

Description=The NGINX HTTP and reverse proxy server

After=syslog.target network-online.target remote-fs.target nss-lookup.target

Wants=network-online.target

[Service]

Type=forking

PIDFile=/usr/local/nginx/logs/nginx.pid

ExecStartPre=/usr/local/nginx/sbin/nginx -t

ExecStart=/usr/local/nginx/sbin/nginx

ExecReload=/usr/local/nginx/sbin/nginx -s reload

ExecStop=/bin/kill -s QUIT $MAINPID

PrivateTmp=true

[Install]

WantedBy=multi-user.target

 

[root@nginx ~]# systemctl daemon-reload

[root@nginx ~]# nginx -s stop

[root@nginx ~]# ps aux | grep nginx

root       42046  0.0  0.1 221664  2304 pts/0    S+   15:57   0:00 grep --color=auto nginx

[root@nginx ~]# systemctl enable --now nginx

Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

配置文件说明

Nginx 的配置文件的组成部分:
    主配置文件: nginx.conf
    子配置文件 : include conf.d/*.conf,fastcgi , uwsgi , scgi 等协议相关的配置文件

主配置文件

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf

核心配置示例

基于不同的 IP 、不同的端口以及不用得域名实现不同的虚拟主机,依赖于核心模块
ngx_http_core_module 实现。

新建一个PC站点

​
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf

events {

    worker_connections  100000;

    use epoll;

}

…

 #gzip  on;

    include "/usr/local/nginx/conf.d/*.conf";

    server {

…

 

[root@nginx ~]# mkdir -p /usr/local/nginx/conf.d

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

}

[root@nginx ~]# mkdir -p /date/web/html

[root@nginx ~]# echo www.timinglee.org > /data/web/html/index.html

 

[root@nginx ~]# 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@nginx ~]# nginx -s reload

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

 

    location = /test {

        root /date/web;

    }

[root@nginx ~]# mkdir /date/web/test -p

[root@nginx ~]# echo test page > /date/web/test/index.html

​

location详细使用

匹配案例
  • 精确匹配
  • 区分大小写
  • 不区分大小写
  • 文件名后缀
  • 优先级
精确匹配
​
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

[root@nginx ~]# nginx -s reload

[root@nginx ~]# mkdir /date/web/test -p

[root@nginx ~]# echo test page > /date/web/test/index.html

 

[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

 

    location = /test {

        root /date/web2;

    }

​

优先级
​
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

 

    location = /test {

        root /date/web2;

    }

 

    location /test {

        root /date/web1;

    }

    location ^~ /t {

        root /date/web3;

    }

    location ~ .html$ {

        root /date/web4;

    }

    location ~* .HTML$ {

        root /date/web5;

    }

}

[root@nginx ~]#

[root@nginx ~]# mkdir -p /date/web{1..5}/test

[root@nginx ~]# echo web1 > /date/web1/test/index.html

[root@nginx ~]# echo web2 > /date/web2/test/index.html

[root@nginx ~]# echo web3 > /date/web3/test/index.html

[root@nginx ~]# echo web4 > /date/web4/test/index.html

[root@nginx ~]# echo web5 > /date/web5/test/index.html
​

 

对目录匹配:

4=5>1>3>2

(~* = ~) > 不带符号 > ^~

注:= 不支持目录

对文件匹配:

= > (~* = ~) > 不带符号 > ^~

 

Nginx用户认证

创建认证文件
​
[root@nginx ~]# yum install httpd-tools

[root@nginx ~]# htpasswd -cm /usr/local/nginx/.htpasswd admin

New password:

Re-type new password:

Adding password for user admin

[root@nginx ~]# htpasswd -m /usr/local/nginx/.htpasswd lee     #-c会覆盖原来的

New password:

Re-type new password:

Adding password for user lee

[root@nginx ~]# cat /usr/local/nginx/.htpasswd

admin:$apr1$HhAqh9XC$3X1Hi5gYYuHONKedAp7lb1

lee:$apr1$FC4uoJ1U$1B47c8l/LiXgMCXJvhs2D1

[root@nginx ~]#

[root@nginx ~]# mkdir /date/web/lee

[root@nginx ~]# echo lee > /date/web/lee/index.html

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

[root@nginx ~]# nginx -s reload

 

[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

 

    location /lee {

        root /date/web;

    }

}

​

设置需要认证可以访问
​
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

 

    location /lee {

        root /date/web;

        auth_basic "login password !!";

        auth_basic_user_file "/usr/local/nginx/.htpasswd";

    }

}

​

自定义错误页面

​
[root@nginx ~]# mkdir -p /date/web/errorpage

[root@nginx ~]# echo error page > /date/web/errorpage/40x.html

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

    error_page 404 /40x.html;

    location /lee {

        root /date/web;

        auth_basic "login password !!";

        auth_basic_user_file "/usr/local/nginx/.htpasswd";

    }

    location = /40x.html {

        root /date/web/errorpage;

    }

}

[root@nginx ~]# nginx -s relod

​

自定义错误日志

[root@nginx ~]# mkdir /var/log/timinglee.org

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

    error_log /var/log/timinglee.org/error.log;

[root@nginx ~]# nginx -s reload

检测日志是否存在

​
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

server {

    listen 80;

    server_name www.timinglee.org;

    root /date/web/html;

    index index.html;

    error_page 404 /40x.html;

    error_log /var/log/timinglee.org/error.log;

    access_log /var/log/timinglee.org/access.log;

    try_files $uri $uri.html $uri/index.html /error/default.html;

    location /lee {

        root /date/web;

        auth_basic "login password !!";

        auth_basic_user_file "/usr/local/nginx/.htpasswd";

    }

    location = /40x.html {

        root /date/web/errorpage;

    }

}

[root@nginx ~]# mkdir /date/web/html/error

[root@nginx ~]# echo error default > /date/web/html/error/default.html

[root@nginx conf.d]# vim /etc/hosts

192.168.86.100  nginx.org www.timinglee.org

[root@nginx conf.d]# curl www.timinglee.org

error default

​

长连接

[root@nginx conf.d]# vim /usr/local/nginx/conf/nginx.conf

    #keepalive_timeout  0;

    keepalive_timeout  65;

    keepalive_requests  2;

测试工具

​
[root@nginx conf.d]# yum install telnet -y

[root@nginx ~]# telnet www.timinglee.org 80

Trying 192.168.86.100...

Connected to www.timinglee.org.

Escape character is '^]'.

GET / HTTP/1.1

Host: www.timinglee.org

    #keepalive_timeout  0;

    keepalive_timeout  5;

    keepalive_requests  500;

[root@nginx ~]# telnet www.timinglee.org 80

Trying 192.168.86.100...

Connected to www.timinglee.org.

Escape character is '^]'.

GET / HTTP/1.1

Host: www.timinglee.org

​

作为下载服务器配置

[root@nginx ~]# mkdir /date/web/download

[root@nginx ~]# dd if=/dev/zero of=/date/web/download/leefile bs=1M count=100

100+0 records in

100+0 records out

104857600 bytes (105 MB, 100 MiB) copied, 0.0459089 s, 2.3 GB/s

[root@nginx ~]# nginx -s reload

    location /download {

        root /date/web;

        autoindex on;

        autoindex_localtime on;      #修改时间

        autoindex_exact_size off;    #显示大小

        limit_rate 1024k;            #限速

    }

Nginx高级配置

Nginx状态页

​
[root@nginx ~]# cd /usr/local/nginx/conf.d/

[root@nginx conf.d]# vim vhost.conf

[root@nginx conf.d]# vim status.conf

[root@nginx conf.d]# nginx -s reload

server {

    listen 80;

    server_name status.timinglee.org;

    root /date/web/html;

    index index.html;

    location /status {

        stub_status;

        #auth_basic "login";

        #auth_basic_user_file "/usr/local/nginx/.htpasswd";

    }

}

[root@nginx conf.d]# vim status.conf

[root@nginx conf.d]# nginx -s reload

[root@nginx conf.d]# vim /etc/hosts

[root@nginx conf.d]# curl status.timinglee.org/status/

<html>

<head><title>403 Forbidden</title></head>

<body>

<center><h1>403 Forbidden</h1></center>

<hr><center>nginx/1.24.0</center>

</body>

</html>

[root@nginx conf.d]#

server {

    listen 80;

    server_name status.timinglee.org;

    root /date/web/html;

    index index.html;

    location /status {

        stub_status;

        #auth_basic "login";

        #auth_basic_user_file "/usr/local/nginx/.htpasswd";

        allow 192.168.86.1;

        deny all;

    }

}

192.168.86.100  nginx.org www.timinglee.org status.timinglee.org

​

Nginx压缩功能

Nginx 支持对指定类型的文件进行压缩然后再传输给客户端,而且压缩还可以设置压缩比例,压缩后的文 件大小将比源文件显著变小,样有助于降低出口带宽的利用率,降低企业的IT 支出,不过会占用相应的CPU 资源。
Nginx 对文件的压缩功能是依赖于模块 ngx_http_gzip_module, 默认是内置模块

[root@nginx conf.d]# vim /usr/local/nginx/conf/nginx.conf
    #keepalive_timeout  0;
    keepalive_timeout  65;
    keepalive_requests 2;

    gzip  on;					#开启gzip压缩功能,
    gzip_comp_level 5;			#设定压缩比为5
    gzip_min_length 1k;			#小于1k的文件就不要压缩了
    gzip_http_version 1.1;		#协议版本设为1.1
    gzip_vary on;				#指定什么类型的文件会被压缩
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/gif image/png;

    include "/usr/local/nginx/conf.d/*.conf";

[root@nginx conf.d]# 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@nginx conf.d]# nginx -s reload    #重新加载

#测试

#大于1k的文件
[root@nginx conf.d]# echo hello timinglee > /data/web/html/small.html
[root@nginx conf.d]# du -sh /usr/local/nginx/logs/access.log
8.0K    /usr/local/nginx/logs/access.log

#小于1k的文件

[root@nginx conf.d]# cat /usr/local/nginx/logs/access.log > /data/web/html/big.html

#查看压缩效果

[root@nginx conf.d]# curl --head --compressed 192.168.86.100/small.html

HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Tue, 20 Aug 2024 15:35:41 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Tue, 20 Aug 2024 15:35:41 GMT
Connection: keep-alive
ETag: "66bf0c8a-10"
Accept-Ranges: bytes

[root@nginx conf.d]# curl --head --compressed 192.168.86.100/big.html
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Tue, 20 Aug 2024 15:35:50 GMT
Content-Type: text/html
Last-Modified: Tue, 20 Aug 2024 15:35:50 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: W/"66bf0cef-1195"
Content-Encoding: gzip

Nginx变量

nginx 的变量可以在配置文件中引用,作为功能判断或者日志等场景使用。

  • 内置变量

Nginx 的内置变量是由 Nginx 核心或模块自动定义的,它们在配置文件中可以直接使用,无需事先声明。这些变量通常包含了请求和响应的详细信息,如客户端IP、请求URI、响应状态码等。

  • 自定义变量

Nginx 允许用户定义自己的变量,这些变量可以在配置文件的任何地方(除了某些特定的上下文)被设置和引用。自定义变量通常用于存储重复出现的值,或者在配置文件中进行条件判断等。

内置变量

[root@nginx conf.d]# vim vars.conf
    
server {

    listen 80;

    server_name var.timinglee.org;

    root /data/web/html;

    index index.html;

 

    location /var {

        default_type text/html;

        echo $remote_addr;    # 存放了客户端的地址,注意是客户端的公网 IP

        echo $args;    # 变量中存放了 URL 中的所有参数

        echo $is_args;     # 如果有参数为 ? 否则为空

        echo $document_root;     # 保存了针对当前资源的请求的系统根目录

        echo $document_uri;    # 保存了当前请求中不包含参数的 URI ,注意是不包含请求的指令

        echo $host;     # 存放了请求的 host 名称

        echo $remote_port;     # 客户端请求 Nginx 服务器时随机打开的端口,这是每个客户端自己的端口

        echo $remote_user;      # 已经经过 Auth Basic Module 验证的用户名

        echo $request_method;      # 请求资源的方式, GET/PUT/DELETE 等

        echo $request_filename;      # 当前请求的资源文件的磁盘路径,由 root 或 alias 指令与 URI 请求生成的文件绝对路径

        echo $request_uri;     # 包含请求参数的原始 URI ,不包含主机名,相当于 :$document_uri?$args

        echo $scheme;     # 请求的协议,例如 :http , https,ftp 等

        echo $server_protocol;     # 保存了客户端请求资源使用的协议的版本

        echo $server_addr;    # 保存了服务器的 IP 地址

        echo $server_name;     # 虚拟主机的主机名

        echo $server_port;     # 虚拟主机的端口号

        echo $http_user_agent;    # 客户端浏览器的详细信息

        echo $http_cookie;    # 客户端的所有 cookie 信息

        echo $cookie_key2;     # name 为任意请求报文首部字部 cookie 的 key 名

    }

}

[root@nginx conf.d]# vim /etc/hosts

[root@nginx conf.d]# curl var.timinglee.org/var

curl -b "key1=lee,key2=lee1" -u lee:lee var.timinglee.org/var?name=lee&&id=6666

自定义变量

#nginx自定义变量

server {

    listen 80;

    server_name var.timinglee.org;

    root /data/web/html;

    index index.html;

 

    location /var {

        default_type text/html;

        set $timinglee lee;

        echo $timinglee;

    }

}



 curl -b "key1=lee,key2=lee1" -u lee:lee var.timinglee.org/var?name=lee&&id=6666

Nginx Rewrite相关功能

ngx_http_rewrite_module模块指令

if指令

用于条件匹配判断,并根据条件判断结果选择不同的 Nginx 配置,可以配置在 server 或 location 块中进行配置,Nginx 的 if 语法仅能使用 if 做单次判断,不支持使用 if else 或者 if elif 这样的多重判断。

    location /test2 {

    if ( !-e $request_filename ){

        echo "$request_filename is not exist";

    }

  }




curl var.timinglee.org/test2/index.html

set指令

指定 key 并给其定义一个变量,变量可以调用 Nginx 内置变量赋值给 key另外set 定义格式为 set $key value , value 可以是 text, variables 和两者的组合。


[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
    server_name www.lee.org;
    root /webdata/nginx/lee.org/lee;
    
    location /test3{
        set $name lee;
        echo $name;
    }
}

break指令

用于中断当前相同作用域 (location) 中的其他 Nginx 配置 与该指令处于同一作用域的Nginx 配置中,位于它前面的配置生效 位于后面的 ngx_http_rewrite_module 模块中指令就不再执行
Nginx 服务器在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,该指令可以在server 块和 locationif 块中使用

    location /break {

        default_type text/html;

        set $name lee;

        echo $name;

        if ( $http_user_agent = "curl/7.76.1" ){

            break;

        }

        set $id 666;

        echo $id;

    }
curl  var.timinglee.org/break

curl -A "firefox"  var.timinglee.org/break

return指令

判定访问文件是否存在,如果不存在返回301,并重定向到百度

​
   location /return {

        default_type text/html;

        if ( !-e $request_filename){

            return 301 百度一下,你就知道;

        }

        echo "$request_filename is exist";

    }

​


 

​
#检测

[root@nginx-node1 conf.d]# curl -I var.timinglee.org/return

HTTP/1.1 301 Moved Permanently

Server: nginx/1.26.2

Date: Sun, 18 Aug 2024 03:01:30 GMT

Content-Type: text/html

Content-Length: 169

Connection: keep-alive

Keep-Alive: timeout=60

Location: 百度一下,你就知道


​

rewrite指令

flag介绍

Nginx中的rewrite指令是实现URL重写和重定向的关键功能之一,它通过正则表达式匹配请求的URI,并将其重写为新的URI,同时支持不同的flag(标志)来调控重写和重定向的行为。

域名永久与临时重定向

[root@nginx-node1 conf.d]# mkdir  -p /data/web/html/return

[root@nginx-node1 conf.d]# curl -I var.timinglee.org/return

HTTP/1.1 200 OK

Server: nginx/1.26.2

Date: Sun, 18 Aug 2024 03:01:58 GMT

Content-Type: text/html

Connection: keep-alive

Keep-Alive: timeout=60

Vary: Accept-Encoding

​
    location / {

        root /data/web/var;

        index index.html;

        rewrite / http://www.timinglee.com permanent; 

        #rewrite / http://www.timinglee.com redirect;

    }

​

301永久,302临时

用浏览器测试,curl不支持重定向

​
[root@nginx-node1 conf.d]# curl -I var.timinglee.org

HTTP/1.1 301 Moved Permanently

Server: nginx/1.26.2

Date: Sun, 18 Aug 2024 03:18:33 GMT

Content-Type: text/html

Content-Length: 169

Connection: keep-alive

Keep-Alive: timeout=60

Location: http://www.timinglee.com


​

自动跳转https

全站加密

cd /usr/local/nginx/

mkdir certs

openssl req  -newkey  rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/timinglee.org.key \

-x509  -days 365 -out /usr/local/nginx/certs/timinglee.org.crt

vim /usr/local/nginx/conf.d/vhosts.conf

​
server {

    listen 80;

    listen 443 ssl;

    server_name www.timinglee.org;

    root /data/web/html;

    index index.html;

    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;

    ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;

    ssl_session_cache    shared:SSL:1m;

    ssl_session_timeout  5m;

​}

判定

​
    location / {

        if ( $scheme = http ){

            rewrite / https://$host redirect;

        }

    }

​

​
server {

    listen 80;

    listen 443 ssl;

    server_name www.timinglee.org;

    root /data/web/html;

    index index.html;

    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;

    ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;

    ssl_session_cache    shared:SSL:1m;

    ssl_session_timeout  5m;

    location / {

        if ( $scheme = http ){

            rewrite /(.*) https://$host/$1 redirect;

        }

        if ( !-e $request_filename ){

            rewrite /(.*) https://$host/index.html redirect;

        }

    }

​

防盗链

防盗链基于客户端携带的 referer 实现, referer 是记录打开一个页面之前记录是从哪个页面跳转过来的标记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗链。

实现盗链

实现防盗链

​
    location /images  {

        valid_referers none blocked server_names *.timinglee.org ~/.baidu/.;

        if ( $invalid_referer ){

                rewrite ^/   http://www.timinglee.org/daolian.png;

        }

    }

​

#盗链网页

<html>



  <head>

    <meta http-equiv=Content-Type content="text/html;charset=utf-8">

    <title>盗链</title>

</head>



  <body>

    <img src="http://www.timinglee.org/images/lee.png" >

    <h1 style="color:red">欢迎大家</h1>

    <p><a href=http://www.timinglee.org>狂点老李</a>出门见喜</p>

  </body>



</html>

Nginx反向代理功能

实现http协议反向代理

[root@nginx ~]# systemctl stop nginx

[root@nginx ~]# cd /usr/local/

[root@nginx local]# rm -fr nginx/

只能写一个

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.timinglee.org;
    location / {
        proxy_pass http://192.168.86.10:80;
    }
}

动静分离

server {
listen 80;
server_name www.timinglee.org;
location ~\.php$ {
proxy_pass http://192.168.86.10:80;
}
location ~ /static {
proxy_pass http://192.168.86.20:8080;
}
}

缓存功能

准备缓存配置

主配置文件中加入

[root@nginx conf.d]# vim vhost.conf

    #gzip  on;

    proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;

​
server {

    listen 80;

    server_name www.timinglee.org;

    location ~ \.php$ {

        proxy_pass http://192.168.86.10:80;

    }

    location /static {

        proxy_pass http://192.168.86.20:8080;

        proxy_cache proxycache;

        proxy_cache_key $request_uri;

        proxy_cache_valid 200 302 301 10m;

        proxy_cache_valid any 1m;

    }

}

​

http反向代理负载均衡

[root@web20 ~]# yum install httpd -y
[root@web20 ~]# echo "web2 192.168.86.20" > /var/www/html/index.html
[root@web20 ~]# systemctl enable --now httpd
 
[root@web10 ~]# yum install httpd -y
[root@web10 ~]# echo "web1 192.168.86.10" >> /var/www/html/index.html
[root@web10 ~]# systemctl enable --now http


[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
upstream webserver {
#ip_hash;
#hash $request_uri consistent;
#hash $cookie_lee
#least_conn;
server 192.168.86.20:8080 weight=1 fail_timeout=15s max_fails=3;
server 192.168.86.10:80 weight=1 fail_timeout=15s max_fails=3;
server 192.168.86.100:80 backup;
}
server {
listen 80;
server_name www.lee.org;
location ~ / {
proxy_pass http://webserver;
}
}

Nginx四层负载均衡


#在web20中安装mysql
[root@web20 ~]# yum install mariadb-server -y
[root@web20 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=20
[root@web20 ~]# systemctl start mariadb
[root@web20 ~]# mysql -e "grant all on *.* to lee@'%' identified by 'lee';"
[root@web10 ~]# mysql -ulee -plee -h192.168.86.20 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
| 20 |
+-------------+

tcp负载均衡要写在http语句块之外

Nginx中


[root@Nginx ~]# vim /apps/nginx/conf/tcp/tcp.conf
stream {
upstream mysql_server {
server 192.168.86.10:80 max_fails=3 fail_timeout=30s;
server 192.168.86.20:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 192.168.86.100:80;
proxy_pass mysql_server;
proxy_connect_timeout 30s;
proxy_timeout 300s;
}
}

fastCGI-php

LNMP-Linux、Nginx、MySQL、PHP

停服务,删掉

[root@nginx ~]# systemctl stop nginx


[root@nginx ~]# cd /usr/local/

[root@nginx local]# ls

bin  etc  games  include  lib  lib64  libexec  nginx  sbin  share  src

[root@nginx local]# rm -rf /usr/local/nginx/

安装模块memc、srcache、php

[root@nginx ~]# tar zxf memc-nginx-module-0.20.tar.gz

[root@nginx ~]# tar zxf srcache-nginx-module-0.33.tar.gz

[root@nginx ~]# cd nginx-1.24.0/

[root@nginx nginx-1.24.0]#


[root@nginx nginx-1.24.0]# ./configure --prefix=/usr/local/nginx --add-module=/root/echo-nginx-module-0.63 --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33 --user=nginx --group=nginx --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-stream --with-stream_ssl_module --with-stream_realip_module --with-pcre

[root@nginx nginx-1.24.0]# make && make install

如果启动失败的话把旧的关了

PHP安装

[root@nginx ~]# tar zxf php-8.3.9.tar.gz

解决依赖、查找依赖包

yum install -y bzip2 systemd-devel libxml2-devel sqlite-devel

libpng-devel libcurl-devel oniguruma-devel

​
wget https://mirrors.aliyun.com/rockylinux/9.4/devel/x86_64/os/Packages/o/oniguruma-devel-6.9.6-1.el9.5.0.1.x86_64.rpm


​

检测模块

./configure --prefix=/usr/local/php --enable-fpm --with-fpm-user=nginx --with-fpm-group=nginx --with-curl --with-iconv --with-mhash --with-zlib --with-openssl --enable-mysqlnd --with-mysqli --with-pdo-mysql --disable-debug --enable-sockets --enable-soap --disable-xml --disable-ftp --disable-gd --disable-exif --enable-mbstring --enable-bcmath --with-fpm-systemd

[root@nginx php-8.3.9]# make && make install

[root@nginx php-8.3.9]# cd /usr/local/php/etc/

[root@nginx etc]# ls

php-fpm.conf.default  php-fpm.d

[root@nginx etc]# cp -p php-fpm.conf.default php-fpm.conf

[root@nginx etc]# vim php-fpm.conf

打开注释

[global]

; Pid file

; Note: the default prefix is /usr/local/php/var

; Default Value: none

pid = run/php-fpm.pid    #这一行打开注释



; Error log file

​
[root@nginx etc]# cd php-fpm.d/

[root@nginx php-fpm.d]# ls

www.conf.default

​
[root@nginx php-fpm.d]# cp www.conf.default www.conf -p

[root@nginx php-fpm.d]# vim www.conf

​[root@nginx php-fpm.d]# cd /root/php-8.3.9/

[root@nginx php-8.3.9]# cp php.ini-production /usr/local/php/etc/php-ini

[root@nginx ~]# cd /usr/local/php/etc/

[root@nginx etc]# vim php.ini

修改主配置文件

date.timezone = Asia/Shanghai

生成启动文件

[root@nginx etc]# cd /root/php-8.3.9/sapi/fpm/

[root@nginx fpm]# cp php-fpm.service /lib/systemd/system/

注释掉

[root@nginx fpm]# vim /lib/systemd/system/php-fpm.service
#ProtectSystem=full

启动

[root@nginx fpm]# systemctl daemon-reload

[root@nginx fpm]# systemctl start php-fpm

准备PHP测试页面

[root@nginx ~]# cd /usr/local/php/bin/

[root@nginx bin]# ls

phar  phar.phar  php  php-cgi  php-config  phpdbg  phpize

[root@nginx bin]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/php/sbin

[root@nginx bin]# source ~/.bash_profile

[root@nginx ~]# mkdir -p /data/web/php

[root@nginx ~]# vim /data/web/php/index.php

[root@nginx php]# vim index.php
<?php

  phpinfo();

?>

进入主配置文件

[root@nginx conf]# vim nginx.conf
   include "/usr/local/nginx/conf.d/*.conf";

[root@nginx nginx]# mkdir conf.d

[root@nginx nginx]# cd conf.d/

[root@nginx conf.d]# vim vhosts.conf
​
server {

    listen 80;

    server_name www.timinglee.org;

    root /data/web/html;

    index index.html;

    location ~ \.php$ {

        root /data/web/php;

        fastcgi_pass 127.0.0.1:9000;

        fastcgi_index index.php;

        include fastcgi.conf;

    }

}

[root@nginx conf.d]# nginx -s reload

​



/usr/local/nginx/logs/error.log    #查看错误日志

​
[root@nginx conf.d]# cd /usr/local/php/etc/php-fpm.d/

[root@nginx php-fpm.d]# vim www.conf
listen = 0.0.0.0:9000
​
[root@nginx conf.d]# systemctl restart php-fpm.service

访问测试

php

安装memcache功能模块

[root@nginx ~]# tar zxf memcache-8.2.tgz
[root@nginx ~]# yum install autoconf -y
[root@nginx memcache-8.2]# phpize

Configuring for:

PHP Api Version:         20230831

Zend Module Api No:      20230831

Zend Extension Api No:   420230831

[root@nginx memcache-8.2]# ./configure && make && make install

[root@nginx memcache-8.2]# cd /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/

[root@nginx no-debug-non-zts-20230831]# ls

memcache.so  opcache.so

[root@nginx no-debug-non-zts-20230831]# cd

[root@nginx ~]# systemctl restart php-fpm.service

[root@nginx etc]# pwd

/usr/local/php/etc

[root@nginx etc]# vim php-ini
extension=memcache

[root@nginx ~]# yum install memcached -y

[root@nginx ~]# vim /etc/sysconfig/memcached

PORT="11211"

USER="memcached"

MAXCONN="1024"

CACHESIZE="64"

OPTIONS="-l 127.0.0.1,::1"

[root@nginx ~]# systemctl start memcached.service

[root@nginx ~]# netstat -antlupe | grep mem

tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      980        149419     159619/memcached

tcp6       0      0 ::1:11211               :::*                    LISTEN      980        149420     159619/memcached

[root@nginx ~]# cd memcache-8.2/

[root@nginx memcache-8.2]# ls

[root@nginx memcache-8.2]# cp example.php memcache.php /data/web/php/

[root@nginx memcache-8.2]# cd /data/web/php/

[root@nginx php]# vim memcache.php
$VERSION='$Id$';



define('ADMIN_USERNAME','admin');   // Admin Username

define('ADMIN_PASSWORD','lee');     // Admin Password

define('DATE_FORMAT','Y/m/d H:i:s');

define('GRAPH_SIZE',200);

define('MAX_ITEM_DUMP',50);



$MEMCACHE_SERVERS[] = '127.0.0.1:11211'; // add more as an array

#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array

​[root@nginx conf.d]# vim vhosts.conf
upstream memcache {

    server 127.0.0.1:11211;

    keepalive 512;

}

server {

    listen 80;

    server_name www.timinglee.org;

    root /data/web/html;

    index index.html;

    location /memc {

        internal;

        memc_connect_timeout 100ms;

        memc_send_timeout 100ms;

        memc_read_timeout 100ms;

        set $memcq_key $query_string;

        set $memc_exptime 300;

        memc_pass memcache;

    }
    location ~ \.php$ {

        root /data/web/php;

        set $key $uri$args;

        srcache_fetch GET /memc $key;

        srcache_store PUT /memc $key;

        fastcgi_pass 127.0.0.1:9000;

        fastcgi_index index.php;

        include fastcgi.conf;

    }

}

​[root@nginx conf.d]# nginx -s reload

Nginx二次开发版本

编译安装openresty


[root@nginx ~]#tar xf openresty-1.17.8.2.tar.gz
[root@nginx ~]#cd openresty-1.17.8.2/
[root@nginx openresty-1.17.8.2]#./configure --prefix=/usr/local/openresty --with-http_realip_module --with-http_sub_module --with-http_gzip_static_module --with-http_stub_status_module --without-http_memcached_module --with-stream_ssl_module --with-stream --with-stream_realip_module --with-pcre --with-http_ssl_module
 
[root@nginx ~]#gmake && gmake install

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值