简介

概念

Nginx (engine x) 是一个高性能的 HTTP 和反向代理 web 服务器,具有低系统消耗、稳定、配置简单的特点,能够支持高达 50000 个并发连接数的响应。

Nginx 入门

安装

linux 安装脚本 install-nginx.sh

安装的 nginx 位置:/usr/local/nginx

配置

nginx 的配置在 conf/nginx.conf

先给出最简单的配置,server_name 改成你自己的公网 ip 即可:

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
worker_processes  1;
events {
worker_connections 1024;
}
http {
server{
listen 80;
server_name 119.91.143.195;
location /{
root html;
}
}
}

运行

服务器执行:

shell
1
nginx

没有任何输出表示运行成功,默认运行端口为 80

运行效果

nginx运行界面

Nginx 常用命令

plaintext
1
nginx
plaintext
1
nginx -s reload
plaintext
1
nginx -s stop

Nginx 的常用场景配置

nginx.conf 配置:

有时候需要将博客部署在服务器作为源站,这时候就需要 nginx 为服务器文件映射给某个端口:

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
worker_processes  1;
events {
worker_connections 1024;
}
http {
server{
listen 8032;
server_name 119.91.143.195;
location /{
root /www/blog;
try_files $uri $uri/ /index.html;
}
}
}

try_files $uri $uri/ /index.html 表示匹配到 / 时先尝试文件 /index.html,成功时返回,失败返回 403,nginx 默认设置。

服务器文件

定义index文件

运行效果

index文件界面

nginx.conf 配置:

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
worker_processes  1;
events {
worker_connections 1024;
}
http {
server{
listen 8032;
server_name 119.91.143.195;
location /{
root /www/blog/aaa/;
try_files $uri $uri/ /index.html;
}
}
}

服务器文件

服务器文件

运行效果

二级页面

反向代理实际上和服务器文件映射类似,都是将本地资源允许其他人访问,通俗叫做本地接口映射

plaintext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
worker_processes  1;
events {
worker_connections 1024;
}
http {
server{
listen 8032;
server_name 119.91.143.195;
location /{
root /www/blog/aaa/;
try_files $uri $uri/ /index.html;
}
location /api/{
proxy_pass http://127.0.0.1:8098/;
proxy_redirect off;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}

运行效果

接口

location /api/ 表示请求的路径严格匹配 api 字段,即请求的路径一定要有 /api/,否则无法匹配到 /api/,nginx 无法匹配 /api1/getName,导致返回了 500 服务器错误:

500错误

location /api 表示含有 /api 就行,故 /api1/getName 匹配成功:

请求路径错误

proxy_pass http://127.0.0.1:8098; 表示匹配路径成功后,将 http://127.0.0.1:8098 的访问结果返回

请求路径错误

请求接口

参考文章

Nginx 官网