小白畅通Linux之旅-----Nginx学习与实战

发布于:2025-06-26 ⋅ 阅读:(23) ⋅ 点赞:(0)

目录

一、 概述

1、Nginx 特点

2、Nginx 作用

3、核心命令

4、Nginx信号

二、nginx安装

1、yum安装

2、编译安装

三、配置案例

1、单站点配置

2、虚拟机主机头配置

四、nginx状态统计

1、本地状态统计

2、vts模块状态统计

五、平滑升级

1、 Nginx平滑升级原理

2、Nginx信号

(1)主进程支持的信号

(2)工作进程支持的信号

3、平滑升级实战

六、反向代理和缓存

1、正向代理和反向代理

(1)正向代理概述

(2)正向代理的作用

(3)正向代理的基本格式

2、反向代理概述

(1)什么是反向代理

(2)反向代理可实现的功能

3、反向代理配置

4、动静分离配置

5、反向代理设置缓存功能

6、实现反向代理客户端IP透传

7、负载均衡

8、 Nginx配置跨域 

(1)跨域的定义

(2)同源的定义

(4)不同源的限制

(5)Nginx 解决跨域的原理

9、防盗链

(1)什么是盗链

(2)如何区分哪些是不正常的用户?

(3) Referer解析

(4)防盗链实战配置


一、 概述

Nginx 是开源、高性能、高可靠的 Web服务器 和反向代理服务器,而且支持热部署,几乎可以做到 7 * 24 小时不间断运行,即使运行几个月也不需要重新启动,还能在不间断服务的情况下对软件版本进行热更新。性能是 Nginx 最重要的考量,其占用内存少、并发能力强、能支持高达 5w 个并发连接数,最重要的是, Nginx 是免费的并可以商业化,配置使用也比较简单。

1、Nginx 特点

  • 高并发、高性能;

  • 模块化架构使得它的扩展性非常好;

  • 异步非阻塞的事件驱动模型(epoll)这点和 Node.js 相似;

  • 相对于其它服务器来说它可以连续几个月甚至更长而不需要重启服务器使得它具有高可靠性;

  • 热部署、平滑升级;

  • 完全开源,生态繁荣。

2、Nginx 作用

  • http服务器。Nginx可以独立提供http服务。可做网页静态服务器。

  • 虚拟主机。可以实现在一台服务器虚拟出多个虚拟服务器。

  • 反向代理,负载均衡。当网站的访问量达到一定程度后,单台服务器不能满足用户的请求时,需要用多台服务器集群可以使用nginx做反向代理。并且多台服务器可以平均分担负载,不会应为某台服务器负载高宕机而某台服务器闲置的情况。

  • nginx 中也可以配置安全管理、比如可以使用Nginx搭建API接口网关,对每个接口服务进行拦截。

Nginx的作用

静态服务 代理服务 安全服务 流行架构
浏览器缓存 协议类型 访问控制 Nginx+PHP(Fastcgi_pass)LNMP
防资源盗用 正向代理 访问限制 Nginx+Java(Proxy_Pass)LNMT
资源分类 反向代理 流量限制 Nginx+Python(uwsgi_pass)
资源压缩 负载均衡 拦截攻击
资源缓存 代理缓存 拦截异常请求
跨域访问 动静分离 拦截SQL 注入

3、核心命令

命令 作用
systemctl enable nginx 开机自动启动
systemctl disable nginx 关闭开机自动启动
systemctl start nginx 启动Nginx
systemctl stop nginx 停止Nginx
systemctl restart nginx 重启Nginx
systemctl reload nginx 重新加载Nginx
systemctl status nginx 查看 Nginx 运行状态
ps -elf | grep [n]ginx 查看Nginx进程,但是不会显示grep本身的进程
kill -9 pid 根据上面查看到的Nginx进程号,杀死Nginx进程,-9 表示强制结束进程
nginx -s reload 向主进程发送信号,重新加载配置文件,热重启
nginx -s reopen 重启 Nginx
nginx -s stop 快速关闭
nginx -s quit 等待工作进程处理完成后关闭
nginx -T 查看当前 Nginx 最终的配置
nginx -t 检查配置是否有问题
nginx -c configfilePath 指定配置文件启动nginx

4、Nginx信号

信号名 含义
stop 直接停止
quit 优雅的退出:有人在访问不会结束进程
reopen 分割日志
reload 重新加载配置文件
term 快速停止nginx进程,可能会中断现有连接,与stop信号类似。
usr1 重新打开日志文件,用于日志切割或日志重定向,与reopen信号类似。
usr2 平滑地升级nginx可执行文件。
hup 重新加载配置文件,优雅地应用新配置,与reload信号类似。
winch 当nginx以master/worker工作模式运行时,重新生成worker进程以适应新的配置。
usr3 向worker进程发送自定义信号。

二、nginx安装

1、yum安装

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

2、编译安装

[root@localhost ~]# cd nginx-1.25.3/
[root@localhost nginx-1.25.3]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@localhost nginx-1.25.3]# ./configure --prefix=/usr/local/nginx
---------------------------------------------------------------

[root@localhost nginx-1.25.3]# make && make install
---------------------------------------------------------------

[root@localhost nginx]# ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx
[root@localhost nginx]# nginx
[root@localhost 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

三、配置案例

1、单站点配置

安装完毕启动nginx服务即可!!

[root@localhost conf]# mv nginx.conf nginx.conf.bak 
[root@localhost conf]# cp nginx.conf.default nginx.conf

[root@localhost conf]# vim nginx.conf
user  nobody; #运行nginx的用户名
worker_processes  2; #启动nginx的work进程数

error_log  logs/error.log; #错误日志存放目录
error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid; #nginx的pid存放目录


events {   #使用equll模型
    worker_connections  1024;
}


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;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;
        charset utf8;

        access_log  logs/access_80.log  main; #访问日志存放目录

        location / {
            root   html;
            index  index.html index.htm;
        }

        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://127.0.0.1;
        #}

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

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


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.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;
    #    }
    #}

}

2、虚拟机主机头配置

(1)基于ip地址

(2)基于端口号

(3)基于域名

四、nginx状态统计

1、本地状态统计

[root@localhost ~]# vim /etc/nginx/nginx.conf
--------------------------------------------
location /nginx_status {
                stub_status on;
                access_log off;
                allow 192.168.75.0/24;
                deny all;
        }
---------------------------------------------

curl 192.168.75.140

Active connections: 2 
server accepts handled requests
 20 20 29 
Reading: 0 Writing: 1 Waiting: 1 

2、vts模块状态统计

user  nginx;
worker_processes  1;
error_log  logs/error.log  info;
pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
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"';
    sendfile        on;
    keepalive_timeout  65;
    gzip  on;
    ##添加如下配置###
    vhost_traffic_status_zone;
    server {
        listen       80;
        server_name  localhost;
        charset utf-8;
        access_log  logs/$server_addr.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }
        ##添加如下配置####
	    location /status {
	        vhost_traffic_status_display;
            vhost_traffic_status_display_format html;
        }
        error_page  404              /404.html;
        location = /404.html {
            root   html;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

五、平滑升级

1、 Nginx平滑升级原理

  • 在不停掉老进程的情况下,启动新进程。

  • 老进程负责处理仍然没有处理完的请求,但不再接受处理请求。

  • 新进程接受新请求。

  • 老进程处理完所有请求,关闭所有连接后,停止。

2、Nginx信号

(1)主进程支持的信号

TERM,INT:立刻退出;

QUIT:等待工作进程结束后再退出;

KILL:强制终止进程;

HUP:重新加载配置文件,使用新的配置启动工作进程,并逐步关闭旧进程;

USR1:重新打开日志文件;

USR2:启动新的主进程,实现热升级;

WINCH:逐步关闭工作进程。

(2)工作进程支持的信号

TERM,INT:立刻退出;

QUIT:等待请求处理结束后再退出;

USR1:重新打开日志文。

3、平滑升级实战

#编译安装nginx1.25.3版本
[root@localhost ~]# cd nginx-1.25.3/
[root@localhost nginx-1.25.3]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@localhost nginx-1.25.3]# ./configure --prefix=/usr/local/nginx
---------------------------------------------------------------

[root@localhost nginx-1.25.3]# make && make install
---------------------------------------------------------------

[root@localhost nginx]# ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx
[root@localhost nginx]# nginx
[root@localhost 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@localhost nginx]# cd conf
[root@localhost conf]# mv nginx.conf nginx.conf.bak
[root@localhost conf]# cp nginx.conf.default nginx.conf
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# netstat -anptu | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      68913/nginx: master 
tcp        0      0 192.168.75.130:80       192.168.75.1:4647       ESTABLISHED 68914/nginx: worker 
tcp        0      0 192.168.75.130:80       192.168.75.1:4648       ESTABLISHED 68915/nginx: worker 
#查看nginx版本
[root@localhost nginx-1.27.3]# nginx -v
nginx version: nginx/1.25.3

#编译安装nginx新版本1.27.3
[root@localhost ~]# ls
公共  视频  文档  音乐  anaconda-ks.cfg       nginx-1.25.3         nginx-1.27.3.tar.gz
模板  图片  下载  桌面  initial-setup-ks.cfg  nginx-1.25.3.tar.gz
[root@localhost ~]# tar -xvf nginx-1.27.3.tar.gz 
--------------------------------------------------------------

[root@localhost nginx-1.27.3]# ./configure --prefix=/usr/local/nginx
[root@localhost nginx-1.27.3]# make
--------------------------------------------------------------

[root@localhost nginx-1.27.3]# ls
auto     CHANGES.ru          conf       contrib          html     Makefile  objs       SECURITY.md
CHANGES  CODE_OF_CONDUCT.md  configure  CONTRIBUTING.md  LICENSE  man       README.md  src
[root@localhost nginx-1.27.3]# cd objs/
[root@localhost objs]# ls
autoconf.err  nginx    ngx_auto_config.h   ngx_modules.c  src
Makefile      nginx.8  ngx_auto_headers.h  ngx_modules.o
[root@localhost objs]# cd
[root@localhost ~]# mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
[root@localhost ~]# cp nginx-1.27.3/objs/nginx /usr/local/nginx/sbin/nginx
#启动新的主进程,实现热升级
[root@localhost ~]# kill -usr2 $(cat /usr/local/nginx/logs/nginx.pid)
[root@localhost ~]# nginx -v
nginx version: nginx/1.27.3

六、反向代理和缓存

1、正向代理和反向代理

(1)正向代理概述

什么是正向代理

正向代理代理的是客户端

正向代理是一个位于客户端和目标服务器之间的代理服务器(中间服务器)。为了从目标服务器取得内容,客户端向代理服务器发送一个请求,并且指定目标服务器,之后代理向目标服务器转发请求,将获得的内容返回给客户端

(2)正向代理的作用

  • 为在防火墙内的局域网客户端提供访问Internet的途径

  • 可以使用缓冲特性减少网络使用率

  • 访问受地理位置限制的网络

  • 使用代理后会隐藏真实的IP地址

(3)正向代理的基本格式

server {
    listen 192.164.65.100:80;
    server_name ....;#客户端访问的域名
​
    location / {
      proxy_pass http://目标服务器地址;
    }
  }

2、反向代理概述

(1)什么是反向代理

反向代理代理的是服务端

反向代理:(reverse proxy),指的是代理外网用户的请求到内部的指定的服务器,并将数据返回给用户的一种方式 客户端不直接与后端服务器进行通信,而是与反向代理服务器进行通信,隐藏了后端服务器的 IP 地址

(2)反向代理可实现的功能

反向代理的主要作用是提供负载均衡和高可用性。

负载均衡:Nginx可以将传入的请求分发给多个后端服务器,以平衡服务器的负载,提高系统性能和可靠性。

缓存功能:Nginx可以缓存静态文件或动态页面,减轻服务器的负载,提高响应速度。

动静分离:将动态生成的内容(如 PHP、Python、Node.js 等)和静态资源(如 HTML、CSS、JavaScript、图片、视频等)分别存放在不同的服务器或路径上。

多站点代理:Nginx可以代理多个域名或虚拟主机,将不同的请求转发到不同的后端服务器上,实现多个站点的共享端口。

3、反向代理配置

源服务器ip:192.168.75.140

[root@localhost ~]# curl 192.168.75.140
狗蛋,来啦

反向代理服务器ip:192.168.75.1304、

在反向代理服务器配置
[root@localhost ~]# vim /etc//nginx/nginx.conf
------------------------------------------------
location / {
                proxy_pass http://192.168.75.140;
        }
-------------------------------------------------
[root@localhost ~]# curl 192.168.75.130
狗蛋,来啦

4、动静分离配置

#Rocky8做php多一步
[root@localhost ~]# vim /etc/php-fpm.d/www.conf
---------------------------------
;listen = /run/php-fpm/www.sock
listen = 127.0.0.1:9000
----------------------------------

[root@localhost ~]# systemctl start php-fpm
[root@localhost html]# rm -rf *
[root@localhost html]# cat index.php 
<?php
echo "<h1>C2505</h1>";
phpinfo();
?>

反向代理服务器配置
[root@localhost ~]# vim /etc/nginx/nginx.conf
-------------------------------------------------
 location /s {
                proxy_pass http://192.168.75.140;
        }
        location /d {
                proxy_pass http://192.168.75.150;
        }
--------------------------------------------------

动态服务器创建d目录
[root@localhost html]# mkdir d
[root@localhost html]# mv index.php d/
静态服务器创建s目录
[root@localhost html]# mkdir s
[root@localhost html]# mv index.html s/

5、反向代理设置缓存功能

[root@localhost ~]# vim /etc/nginx/nginx.conf
proxy_cache_path /data/nginx/proyxcache#缓存目录   levels=1:1:1 keys_zone=proxycache:20m inactive=120s max_size=1g;
server {
    listen       80;
        server_name  localhost;
   proxy_cache proxycache;  #打开缓存功能
   proxy_cache_key $request_uri;  #缓存内容
   #proxy_cache_key $host$uri$is_args$args;
   proxy_cache_valid 200 302 301 10m; #缓存页面 缓存时间
   #proxy_cache_valid any 5m; #其他缓存
   server_name  localhost;
  
  location /s {
                proxy_pass http://192.168.75.140;
        }
   location /d {
                proxy_pass http://192.168.75.150;
        }

6、实现反向代理客户端IP透传

[root@localhost ~]# vim /etc/nginx/nginx.conf
location /s/ {
                proxy_pass http://192.168.75.140;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        location /d/ {
                proxy_pass http://192.168.75.150;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
动态服务器访问(ip:192.168.75.150)
[root@localhost php-fpm.d]# curl 192.168.75.130/s/index.html
狗蛋,来啦

静态服务器查看穿透ip
[root@localhost logs]# tail -f access_80.log 
192.168.75.130 - - [24/Jun/2025:11:29:11 +0800] "GET /s/index.html HTTP/1.0" 200 16 "-" "curl/7.61.1" "192.168.75.150"

7、负载均衡

#反向代理服务器配置
[root@localhost ~]# vim /etc/nginx/nginx.conf
------------------------------------------------
http {
    include       mime.types;
    default_type  application/octet-stream;
------------------------------------------------
    upstream web-servers {
            server 192.168.75.140 weight=1;
            server 192.168.75.150 weight=2;
    }
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;
        charset utf8;
        location / {
                proxy_pass http://web-servers;
        }
---------------------------------------------------

测试
[root@localhost ~]# curl 192.168.75.130
192.168.75.140
[root@localhost ~]# curl 192.168.75.130
192.168.75.150
[root@localhost ~]# curl 192.168.75.130
192.168.75.150


##做该配置时需将动静分离配置删掉或注释

每个请求按访问IP的哈希结果分配,使来自同一个IP的访客固定访问一台后端服务器,并且可以有效解决动态网页存在的session共享问题
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
 upstream web-servers {
            ip_hash;
            server 192.168.75.140 weight=1;
            server 192.168.75.150 weight=2;
    }

8、 Nginx配置跨域 

(1)跨域的定义

同源策略限制了从同一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。通常不允许不同源间的读操作。

(2)同源的定义

如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源。

与 URL http://store.company.com/dir/page.html 的源进行对比的示例:

(4)不同源的限制

  • Web 数据层面,同源策略限制了不同源的站点读取当前站点的 Cookie 、 IndexDB 、 LocalStorage 等数据;

  • DOM 层面,同源策略限制了来自不同源的 JavaScript 脚本对当前 DOM 对象读和写的操作;

  • 网络层面,同源策略限制了通过 XMLHttpRequest 等方式将站点的数据发送给不同源的站点。

(5)Nginx 解决跨域的原理

浏览器的同源策略限制了跨域请求,但当使用 Nginx 作为代理服务器时,浏览器发送的请求实际上是发送到与前端页面同源的 Nginx 服务器。然后 Nginx 将请求转发到真正的目标服务器,目标服务器返回的响应再通过 Nginx 返回给浏览器。从浏览器的角度看,它只与同源的 Nginx 服务器进行交互,从而绕过了 CORS 限制

总结:nginx能解决跨域的问题,利用的是反向代理的特性,通过servername与前端服务器保持同源

9、防盗链

(1)什么是盗链

  • 在实际生产过程中,我们线上的图片等静态资源,经常会被其他网站盗用,他们发大财的同时,成本确实我们在买单,下面来说下,如何杜绝这种行为。

  • 应该说只要是静态资源都是可以防盗链的,只需要在Server字段加上几行代码即可。众所周知网站出名了后,会有各种刁民来找茬的,最常见的就是爬你网站的东西。

  • 关于防盗链这里不得不提一下网页的加载顺序是先加载HTML相关的内容,然后解析HTML的内容,那些需要加载图片,那些需要加载文件,是逐步加载的,所以可以在加载静态资源的时候做防盗链的操作,例如:在加载图片的时候直接跳转去其他链接,或者直接返回404,403等错误代码,拒绝它的请求。

(2)如何区分哪些是不正常的用户?

  • HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如防止未经允许的网站盗链图片、文件等。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况.

  • 比如在www.google.com 里有一个 www.baidu.com 链接,那么点击这个www.baidu.com ,它的header 信息里就有:Referer=http://www.google.com

(3) Referer解析

  • HTTP 协议中有一个用来表示“页面或资源”来源的“请求头”,这个请求头叫做 Referer --> Referer是表示请求是从哪个网址发出的防盗链功能基于HTTP协议支持的 Referer 机制,通过Referer跟踪来源,对来源进行识别和判断

(4)防盗链实战配置

1、设置盗链文件(其他服务器上配置)
[root@localhost ~]# vim /usr/share/nginx/html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产生盗链</title>
</head>
<body>
 <a href='http://192.168.75.140/photos/1.png'>站点</a>
</body>
</html>

2、源文件编写防盗链文件
[root@localhost nginx]# vim /etc/nginx/nginx.conf
-------------------------------------------------
server {
        listen       80;
-------------------------------------------------
valid_referers none blocked 192.168.75.130;
        if ($invalid_referer){
                return 403;
                }
-------------------------------------------------

给源主机静态资源做referer
[root@localhost s]# cat index.html 
狗蛋,来啦
<a href='http://192.168.75.140/photos/1.png'>图片</a>


网站公告

今日签到

点亮在社区的每一天
去签到