nginx

nginx

niginx

Nginx (“engine x”) 是一款开源的,支持高性能、高并发的 Web 服务和代理服务软件,因为稳定性、丰富的模块库、灵活的配置和低系统资源的消耗而闻名

nginx 提供的服务

  • web 服务

  • 负载均衡 (反向代理)

  • web cache(web 缓存)

nginx 优点

  • 比其他服务器响应更快

  • 高扩展,nginx的设计极具扩展性,他是由多个功能不同且耦合性极低的模块组成。

  • 单机支持并发极高,理论上支持10万的并发连接,nginx支持的并发连接和内存相关

  • 低内存消耗,10000个非活跃的http keep-alive链接在nginx中仅仅消耗2.5M的内存。

  • 支持热部署,如不用停止服务就能重新加载配置文件。

nginx 应用场景

  • 静态服务器。存放我们的静态资源。

  • 反向代理,负载均衡。日pv2000W以下,都可以直接用nginx做代理。

  • 缓存服务

Linux安装nginx

虚拟机安装Linux

首先下载一个liunx镜像,然后使用虚拟机配置就可以了,系统安装完之后配置虚拟机的liunx网卡配置,使其可以进行上网,首先修改其配置文件,指令为cd /etc/sysconfig/network-scripts/然后修改其文件 指令 vi ifcfg-ens33

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
TC0YPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=d713ec89-fbca-42ff-8d10-3768d86f12a1
DEVICE=ens33
ONBOOT=yes
IPADDR=192.168.117.200
NETMASK=255.255.255.0
GATEWAY=192.168.117.2
DNS1=114.114.114.114
DNS2=114.114.115.115

这里面修改的有BOOTPROTO=static 设置为static静态,ONBOOT=yes设置为yes然后后面是新增的配置

1
2
3
4
5
IPADDR=192.168.117.200
NETMASK=255.255.255.0
GATEWAY=192.168.117.2
DNS1=114.114.114.114
DNS2=114.114.115.115

然后重启网卡 指令为:systemctl restart network

ip addr 查看网卡信息

ping www.baidu.com 测试是否可以上网,检验是否连通

linux安装nginx

安装wget工具 yum install wget -y

安装vim工具 yum install vim -y

安装netstat工具 yum install net-tools -y

然后解压 tar -zxvf nginx-1.22.0.tar.gz

然后对其进行配置 ./configure --prefix=/data/nginx --user=nginx --group=nginx --with-http_ssl

创建存放nginx的目录 mkdir /data/nginx -p

sbin/目录特殊进行设置 useradd nginx -M -s /sbin/nologin

编译安装 make && make install

进入其sbin目录 cd sbin/

运行nginx ./nginx

查看其运行状态 netstat -nplt 或者 ps -aux | grep nginx

查看端口号(额外命令) netstat -ano | findstr 端口号 或者 netstat -anp | grep 端口号

暂时关闭所有防火墙 systemctl stop firewalld

永久关闭防火墙 systemctl disable firewalld

重启防火墙 systemctl enable firewalld

查看防火墙状态 systemctl status firewalld

此时就可以访问了 我这里面访问的地址是 192.162.117.200 这个是你linux的网卡地址

curl 地址 linux中地址访问

nginx基本命令

./mginx 启动

nginx -s stop 立马关闭

nginx -s quit 优雅关闭,处理完没处理好的请求后关闭

nginx -s reload 重新加载配置文件

nginx -s reopening the log files 用来打开日志文件,这样nginx会把新日志信息写入这个新的文件中

nginx配置

首先这里先介绍一下目录结构

conf nginx的主要配置在这里配置着

html 项目存放在这里

logs 日志存放目录

sbin nginx启动项

......_temp nginx运行时的一些临时文件

基本配置文件

  • nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#user  nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#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"';

#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;

#access_log logs/host.access.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;
# }
#}

}

配置划分

1
2
3
4
5
6
7
8
main{ #(全局设置)
http{ #服务器配置
upstream{} #(负载均衡服务器设置)
server{ #(主机设置:主要用于指定主机和端口)
location{} #(URL匹配的设置)
}
}
}

nginx配置文件结构

前后端实战演示

前端搭建

前端使用vue_cli快速搭建

前端这里去掉#,在router里进行设置

1
2
3
4
5
6
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
history: createWebHistory(),
routes
})

前端只是简单的使用axios发送一个请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
</div>
The Serever Port Number is {{ host }}
</template>

<script>
import axios from 'axios'

export default {

data(){
return{
host: '',
}
},

mounted(){

var ip_addr = document.location.hostname;

axios.get("http://" + ip_addr + "/api/host").then(res =>{
this.host = res.data;
})
},
components: {

}
}
</script>

后端搭建

快速搭建springboot项目,写一个Controller返回其端口号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.dream.xiaobo.controller;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
public class NginxController implements ApplicationListener<WebServerInitializedEvent> {
private Integer port;

@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
//获取到端口号
this.port = event.getWebServer().getPort();
}

/**
* 获取本机的IP地址
* @return
*/
@GetMapping("host")
public String getHost(){
InetAddress address;
try {
address = InetAddress.getLocalHost();
return address.getHostAddress() + ":" + port;
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "error:Network card information is not available!";
}
}

nginx做静态服务器

  • nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#user  nobody;
worker_processes 1;
error_log /data/nginx/logs/error.log crit;
pid /data/nginx/logs/nginx.pid;
worker_rlimit_nofile 65535;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

# 主要是nginx和用户交互网络连接优化的配置内容
events {
worker_connections 1024;
# worker_connections 65536;
}


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;

#charset gb2312;
sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;
# 开启图片gzip压缩
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 5;
gzip_types image/png;
gzip_vary on;

server {

listen 80;
server_name www.xbconding.com;
index index.html index.htm index.php;
root /data/www;

#charset koi8-r;

#access_log logs/host.access.log main;

# 寻找路径 try_files依次寻找
location / {
root /data/www/ui;
try_files $uri $uri/ $uri/index.html $uri.html /index.html;
}

# @other 寻找下一个是@other的location
location ^~ /backend {
root /data/www;
try_files /a/b.html $uri $uri/index.html $uri.html @other;
}

# proxy_pass 代理的服务器
location @other {
proxy_pass http://127.0.0.1:8888;
}

# index 显示
location ^~ /image {
root /data/www;
index 1.jpg;
}

# 跨域代理 rewrite重写uri
location ^~ /api/ {
rewrite ^/api(.*)$ $1 break;
proxy_pass http://127.0.0.1:8080;
}

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;
# }
#}

}

listen 80; 监听端口,默认80,小于1024的要以root启动

server_name 用于设置虚拟主机服务名称

root /data/www 定义服务器的默认网站根目录位置。

index 定义路径下默认访问的文件名,一般和root一起出现

error_page 重定向页面

location 配置项

location通常用来匹配uri

1
location [=|~|~*|^~] /uri/ {}

= 表示匹配uri时必须做到完全匹配

~ 表示匹配URI时是字母大小写敏感的,可以使用正则表达式

~* 表示匹配URI时是忽略字母大小敏感的,可以使用正则表达式

^~ 表示匹配uri时只需满足前缀匹配即可

/ 匹配所有的uri

@ 指定一个命名的location,一般用于内部重定义请求

匹配优先顺序

= > ^~ > ~* > / 尽量将 = 放在前面

反向代理解决跨域

1
2
3
4
location ^~ /api/ {
rewrite ^/api(.*)$ $1 break;
proxy_pass http://127.0.0.1:8080;
}
1
2
3
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/;
}

都可以解决,就是做个代理

rewrite break:url重写后,直接使用当前资源,不再执行location里余下的语句,完成本次请求,地址栏url不变

rewrite last:url重写后,马上发起一个新的请求,再次进入server块,重试location匹配,超过10次匹配不到报500错误,地址栏url不变

rewrite redirect:返回302临时重定向,地址栏显示重定向后的url

  • 添加响应首部
1
2
3
4
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow_Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

负载均衡

1
2
3
4
5
6
7
8
9
10
11
#     服务器做负载均衡
upstream dreamServer {
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8082;
}
# 跨域代理 rewrite重写uri
location ^~ /api/ {
rewrite ^/api(.*)$ $1 break;
proxy_pass http://dreamServer;
}

负载均衡五中算法

  • round robin 轮询 (默认)
1
2
3
4
upstream dreamServer {
server 127.0.0.1:8080;
server 127.0.0.1:8082;
}

按时间顺序依次将请求分配到各个后台服务器中,挂掉的服务器自动从列表中剔除

  • weight 轮询权重
1
2
3
4
upstream dreamServer {
server 127.0.0.1:8080 weight=20;
server 127.0.0.1:8082 weight=10;
}

weight的值越大分配到的访问概率越高,主要用于后端每台服务器性能不均衡的情况下,或在主从的情况下设置不同的权值,达到合理有效的地利用主机资源

  • ip_hash
1
2
3
4
5
upstream dreamServer {
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8082;
}

每个请求按访问IP的哈希结果分配,使来自同一个IP的访客固定访问一台后端服务器,并且可以有效解决动态网页存在的session共享问题

  • url_hash
1
2
3
4
5
6
upstream dreamServer {
server 127.0.0.1:8080;
server 127.0.0.1:8082;
hash $request_uri;
hash_method crc32; //使用hash算法
}

按访问的URL的哈希结果来分配请求,使每个URL定向到同一台后端服务器,可以进一步提高后端服务器缓存的效率。Nginx本身不支持url_hash,需要安装Nginx的hash软件包

  • fair算法
1
2
3
4
5
upstream dreamServer {
server 127.0.0.1:8080;
server 127.0.0.1:8082;
fair;
}

可以根据页面大小和加载时间长短智能地进行负载均衡,根据后端服务器的响应时间来分配请求,响应时间短的优先分配。Nginx本身不支持fair,要安装upstream_fair模块才能使用

代理反向代理

  • 代理
    代理

代理是你知道目标服务器,你想要访问目标服务器,但是这个时候你是访问不到的,所以这个时候你要先访问代理服务器,通过代理服务器才可以访问到目标服务器

  • 反向代理
    反代理

反向代理是你想要访问目标服务器,但是你不知道目标服务器,所以这个时候需要一个反向代理服务器,因为我们知道反向代理服务器,所以我们要通过反向代理服务器才可以访问到目标服务器

nginx监控

1
2
3
4
#设定查看Nginx状态的地址
location = /status {
stub_status on; #表示开启stubStatus的工作状态统计功能。
}
  • 访问地址
    curl http://地址/status

  • 状态码

状态码 含义
Active connections 当前所有处于打开状态的连接数
accepts 总共处理了多少个连接
handled 成功创建多少握手
requests 总共处理了多少个请求
Reading 表示正处于接收请求状态的连接数
Writing 表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数
Waiting 开启keep-alive的情况下,这个值等于active - (reading + writing),意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

nginx控制访问

1
2
3
4
5
6
7
location /status {
stub_status on;
access_log off;
allow *.*.*.*;
allow *.*.*.*/0;
deny all;
}

允许或禁止某个ip或ip段访问,依次满足任何一个规则就停止往下匹配

nginx目录资源

1
2
3
4
5
6
7
location ^~ /file {
root /data/www;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
charset utf-8,gbk;
}

autoindex on;运行列出目录内容。

autoindex_exact_size off; 默认为on,显示出文件的确切大小,单位是bytes。改为off后,显示出文件的大概大小,单位是kB或者MB或者GB。

autoindex_localtime on; 默认为off,显示的文件时间为GMT时间。改为on后,显示的文件时间为文件的服务器时间。

charset utf-8,gbk; 编码

正确的开始 微小的长进 然后持续 嘿 我是小博 带你一起看我目之所及的世界……

-------------本文结束 感谢您的阅读-------------

本文标题:nginx

文章作者:小博

发布时间:2022年09月16日 - 20:11

最后更新:2022年09月16日 - 20:24

原始链接:https://codexiaobo.github.io/posts/2759310851/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。