Nginx 教程

HTTP服务器、反向代理和负载均衡器的完整配置指南

关于 Nginx

开发者:Igor Sysoev

类型:HTTP服务器、反向代理、负载均衡器

许可证:2-clause BSD License

官网:nginx.org

预览

本教程具体可以帮助到的范围:

演示环境

设备

  1. 设备A,macOS,充当客户端
  2. 设备B,Ubuntu,充当服务器

网络环境

A、B在同一个局域网内

模拟域名解析

修改了设备A的 /etc/hosts

hosts文件配置
1 192.168.1.25 example.com www.example.com jupyter.example.com

这一步相当于模拟设置了域名解析:将 example.com www.example.com jupyter.example.com 三个网址解析到了 192.168.1.25

Nginx 安装

安装命令
1 sudo apt update && sudo apt install -y nginx

Systemd控制nginx

Systemd 控制命令
1 sudo systemctl status nginx # 查看nginx运行状态
2 sudo systemctl reload nginx # 重新加载nginx的配置文件
3 sudo systemctl stop nginx # 关闭nginx,直到下次开机或者start
4 sudo systemctl start nginx # 启动nginx
5
6 sudo systemctl disable nginx # 关闭nginx自动启动
7 sudo systemctl enable nginx # 开启nginx自动启动

静态网站的部署

准备好HTML文件

假设你准备好的HTML的路径:/path/to/html/index.html

该路径建议使用 /var/www/html 或者 /usr/share/nginx/html

其他路径需要修改权限,权限不对会导致403错误

修改配置文件并reload nginx

编辑配置文件
1 sudo vim /etc/nginx/nginx.conf

在 http 的 scope 内添加:

nginx.conf 配置
1 server {
2 listen 80 default_server; # 当客户端请求没有匹配任何 server_name,就使用这个 default_server 作为"兜底"处理。
3 listen [::]:80 default_server;
4 server_name _;
5 # server_name example.com www.example.com; # 如果有域名的话
6
7 location / {
8 root /path/to/html;
9 index index1.html;
10 }
11 }
12
13 server {
14 listen 2280;
15 server_name _;
16 # server_name example.com www.example.com; # 如果有域名的话
17
18 location / {
19 root /path/to/html;
20 index index2.html;
21 }
22 }
重新加载配置
1 sudo systemctl reload nginx

名称虚拟主机(Name-based virtual servers)

虚拟主机配置
1 server {
2 listen 80;
3 server_name www.example.com;
4 # server_name example.com www.example.com; # 如果有域名的话
5
6 location / {
7 root /path/to/html;
8 index index1.html;
9 }
10 }
11
12 server {
13 listen 80;
14 server_name blog.example.com;
15 # server_name example.com www.example.com; # 如果有域名的话
16
17 location / {
18 root /path/to/html;
19 index index2.html;
20 }
21 }

反向代理

反向代理配置
1 server {
2 listen 3280;
3 server_name _;
4 # server_name example.com www.example.com; # 如果有域名的话
5
6 location / {
7 proxy_pass http://127.0.0.1:8888;
8 }
9 }

SSL证书

SSL配置
1 server {
2 listen 80;
3 listen [::]:80;
4 server_name _;
5
6 # 将 HTTP 请求重定向到 HTTPS
7 return 301 https://$host$request_uri;
8 }
9
10 server {
11 listen 443 ssl;
12 listen [::]:443 ssl;
13 server_name _;
14
15 root /var/www/html;
16 index index.html index.htm index.nginx-debian.html;
17
18 ssl_certificate /etc/ssl/certs/your_domain.crt;
19 ssl_certificate_key /etc/ssl/private/your_domain.key;
20
21 ssl_protocols TLSv1.2 TLSv1.3;
22 ssl_ciphers HIGH:!aNULL:!MD5;
23 ssl_prefer_server_ciphers on;
24
25 location / {
26 try_files $uri $uri/ =404;
27 }
28 }

删除nginx

卸载命令
1 sudo systemctl stop nginx # 先停下来
2 sudo apt purge nginx nginx-common nginx-full -y # 注意: purge 会移除配置文件,remove 不会,可能会没有清除html文件
3 sudo apt autoremove --purge -y # 可选,清除残留依赖