Linux运维新手的修炼手扎之第20天

Nginx基础

1 nginx配置

注:关于主程序配置相关的属性修改,尽量用restart ; server级别 \| 被include级别的配置,尽量用reload

配置结构:全局配置、event配置、http配置、server配置、location配置

复制代码
# 执行命令过滤nginx配置文件非注释和非空行
	root@ubuntu24-13:~# grep -Ev '#|^$' /etc/nginx/nginx.conf
	#全局配置------------------------------------------------------------------------------
	user www-data; # 指定worker进程运行用户
	worker_processes auto; # 自动根据CPU核心数设置worker进程数,在一个4核CPU的服务器上,worker_processes auto会自动开启4个worker进程;在8核CPU上则开启8个
	pid /run/nginx.pid;  # master进程PID文件路径
	error_log /var/log/nginx/error.log; #错误日志路径
	include /etc/nginx/modules-enabled/*.conf;  #将不同模块的配置与主配置文件(nginx.conf)解耦,使配置更易维护[此方式仅适用于动态模块(.so 文件)静态编译的模块(通过 --add-module)无需此配置,已内置到Nginx二进制文件中]

#events配置---------------------------------------------------------------------------
	events {
    	worker_connections 768;  # 每个worker可以维持768个连接 # 2核默认开启两个worker,并发数为 768*2(总并发≈worker_processes×worker_connections)
	}

#http配置-----------------------------------------------------------------------------
	http {
        ...
        include /etc/nginx/conf.d/*.conf; #引用其它配置文件,此目录默认为空
        include /etc/nginx/sites-enabled/*; #虚拟主机配置,每个虚拟主机一个文件
	}

删除默认配置---root@ubuntu24-13:~# rm -f /etc/nginx/sites-enabled/default
	定制配置文件---vim /etc/nginx/conf.d/vhost.conf
	#server配置:
	server {
        listen 80 default_server;
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name www.a.com;
        location / {
            try_files $uri $uri/ =404;
        }
}
复制代码
#location配置-------------------------------------------------------------------------
        location配置段匹配规则:[= 精确匹配,区分大小写;^~ 以特定字符串开始,区分大小写;~ 区分大小写;~* 不区分大写;/str 匹配以str开头的uri,/也是一个字符(兜底规则);\ 可以将 . * ?等转义为普通符号]
        规则优先级:=  >  ^~  >  ~*  >  ~  >  /str
       location = /login {
            echo "规则A";
        }
        location ^~ /static/ {
            echo "规则B";
        }
        location ~ \.(gif|jpg|png|js|css)$ {
            echo "规则C";
        }
        location ~* \.png$ {
            echo "规则D";
        }
        location /img {
            echo "规则E";
        }
        location / {
            echo "规则F";
        }
        注:$ 是正则表达式的元字符,用于匹配字符串的结束位置

location 匹配的路径必须以 / 结尾,否则可能导致匹配异常,root保留location匹配部分,追加到 root 后,通常不写 / ,alias删除location匹配部分,用alias替换,必须以"/"结尾

2 日志管理:

定制日志: logformat 日志格式名 "内容格式"
log_format combined 'remote_addr - remote_user [time_local\] ' '"request" status body_bytes_sent '
'"http_referer" "http_user_agent"';
使用日志: access_log|error_log 日志路径
access_log /var/log/nginx/access.log 日志格式名;
error_log /var/log/nginx/error.log;

3 其他实践:

rewrite:

将带斜杠的URL重定向到不带斜杠,Nginx返回HTTP301状态码,并跳转到/$1

rewrite ^/(.*)/ /1 permanent;[rewrite--重写 ; ^/(.*)/--匹配/xxx/格式的路径,.\* 捕获任意字符 ; /1--引用正则中 (.*) 捕获的内容,输入 /about/→匹配 (.*) 为about→替换为/about ; permanent--重定向类型,返回301永久重定向,浏览器会缓存此跳转]
(1)在正则表达式 ^/(.*)/ 中,(.\*) 是一个捕获组,它会匹配任意字符(除了换行符)并保存到1如:请求URL是/about/→(.*) 匹配到about,所以1 = about ; 请求URL是/posts/123/→(.\*) 匹配到posts/123,所以1 = posts/123
(2)如果正则中有多个捕获组按顺序编号:rewrite ^/(user)/(\d+)/ /profile/2 permanent;/user/123/→重写为/profile/123(1 = user, 2 = 123)

复制代码
root@ubuntu24-13:~#vim /etc/nginx/conf.d/vhost.conf
        server {
            listen 80 default_server;
            root /data/server/nginx/web1;
            location /1.html {
                # break结束当前server配置段中的所有rewrite
                rewrite /1.html /a.html break; # 访问1跳转到a
                rewrite /a.html /3.html; # 访问a跳转到3
            }
            location /2.html {
                # last结束当前location中的本轮rewrite,继续执行下一轮rewrite,一个location是一轮
                rewrite /2.html /a.html last; # 访问2跳转到a
                rewrite /a.html /3.html; # 访问a跳转到3
            }
            location /a.html {
                rewrite /a.html /b.html; # 访问a跳转到b
            }
        }
        curl 10.0.0.13/1.html[访问 1 跳转到 a, 遇到 break, 不再跳了]
        curl 10.0.0.13/2.html[访问 2 跳转到 a, 访问 a 跳转到 b]

重定向:

永久重定向301---permanent,跳转后的目标长时间段里面不会发生改变

将所有请求永久重定向到新域名

return 301 http://new.example.comrequest_uri;(推荐) rewrite \^/(.\*) http://new.example.com/$1 permanent;
临时重定向302---redirect,跳转后的目标短时间段里面不会发生改变,长时间有可能随时更换

将所有请求临时重定向到维护页面

return 302 http://example.com/maintenance.html;(推荐)
rewrite ^/(.*) http://example.com/maintenance.html redirect; 内置变量: request_uri用于获取客户端请求的完整 URI(包括路径和查询参数)
假设客户端请求的URL是:https://example.com/products/search?keyword=phone\&page=2
Nginx变量的值分别为:
request_uri→/products/search?keyword=phone\&page=2 uri→/products/search
$args→keyword=phone&page=2

4 反向代理:

核心配置:proxy_pass、proxy_set_header

复制代码
定制配置文件:
	root@ubuntu24-13:~#vim /etc/nginx/conf.d/vhost.conf 
    server {
        listen 80 default_server;
        server_name sswang.magedu.com; #定义域名匹配请求的Host头(如http://sswang.magedu.com)
        root /data/server/nginx/web1; #设置网站根目录
        location /api {
            proxy_pass http://10.0.0.16:8080;
            proxy_set_header Host "api.magedu.com"; #修改转发请求的Host头为api.magedu.com
        }
        location /static {
            rewrite ^/static(.*)$ /index.html break; #将 /static 开头的 URL 重写为 /index.html(例如,/static/js/app.js → /index.html),但不继续匹配其他 location 块(break 终止规则)
            proxy_pass http://10.0.0.14;
            proxy_set_header Host "static.magedu.com";
            # 将客户端IP追加请求报文中X-Real-IP,记录客户端的真实IP地址。
            proxy_set_header X-Real-IP \$remote_addr;
            # 将客户端IP追加请求报文中X-Forwarded-For首部字段
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        }
	}
	重启服务:root@ubuntu24-13:~# systemctl restart nginx
	客户端测试效果:[root@rocky9-12 ~]# curl 10.0.0.13/static
	客户端:10.0.0.13---真实ip: 10.0.0.12----地址列表:10.0.0.12

5 负载均衡:upstream [和server处于同一个级别]

复制代码
配置定制:
			root@ubuntu24-13:~# vim /etc/nginx/conf.d/vhost.conf
            upstream group1 {
                # 定制一个 三比一 的权重负载效果
                server 10.0.0.16 weight=3;
                server 10.0.0.14;
            }
            server {
                listen 80 default_server;
                location / {
                    proxy_pass http://group1;
                }
            }
         重启服务:root@ubuntu24-13:~# systemctl restart nginx
         测试效果[root@rocky9-12 ~]# curl 10.0.0.13
         
[注:curl -H "Host: sswang.magedu.com" http://10.0.0.13 可绕过DNS解析,如果域名DNS未生效或本地 /etc/hosts未配置,可以直接用 IP + Host 头访问目标网站]