超实用 Nginx 极简教程,覆盖了常用场景

新闻 系统运维
Nginx (engine x) 是一款轻量级的 Web 服务器 、反向代理服务器及电子邮件(IMAP/POP3)代理服务器。

 [[331054]]

概述

什么是 Nginx?

Nginx (engine x) 是一款轻量级的 Web 服务器 、反向代理服务器及电子邮件(IMAP/POP3)代理服务器。

什么是反向代理?

反向代理(Reverse Proxy)方式是指以代理服务器来接受 internet 上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。

使用

nginx 的使用比较简单,就是几条命令。

常用到的命令如下:

  1. nginx -s stop       快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。 
  2. nginx -s quit       平稳关闭Nginx,保存相关信息,有安排的结束web服务。 
  3. nginx -s reload     因改变了Nginx相关配置,需要重新加载配置而重载。 
  4. nginx -s reopen     重新打开日志文件。 
  5. nginx -c filename   为 Nginx 指定一个配置文件,来代替缺省的。 
  6. nginx -t            不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。 
  7. nginx -v            显示 nginx 的版本。 
  8. nginx -V            显示 nginx 的版本,编译器版本和配置参数。 

如果不想每次都敲命令,可以在 nginx 安装目录下新添一个启动批处理文件startup.bat,双击即可运行。内容如下:

  1. @echo off 
  2. rem 如果启动前已经启动nginx并记录下pid文件,会kill指定进程 
  3. nginx.exe -s stop 
  4.  
  5. rem 测试配置文件语法正确性 
  6. nginx.exe -t -c conf/nginx.conf 
  7.  
  8. rem 显示版本信息 
  9. nginx.exe -v 
  10.  
  11. rem 按照指定配置去启动nginx 
  12. nginx.exe -c conf/nginx.conf 

如果是运行在 Linux 下,写一个 shell 脚本,大同小异。

nginx 配置实战

我始终认为,各种开发工具的配置还是结合实战来讲述,会让人更易理解。

我们先实现一个小目标:不考虑复杂的配置,仅仅是完成一个 http 反向代理。

nginx.conf 配置文件如下:

注:conf / nginx.conf 是 nginx 的默认配置文件。你也可以使用 nginx -c 指定你的配置文件

  1. #运行用户 
  2.  
  3. #user somebody; 
  4.  
  5. #启动进程,通常设置成和cpu的数量相等 
  6.  
  7. worker_processes 1
  8.  
  9. #全局错误日志 
  10.  
  11. error_log D:/Tools/nginx-1.10.1/logs/error.log; 
  12.  
  13. error_log D:/Tools/nginx-1.10.1/logs/notice.log notice; 
  14.  
  15. error_log D:/Tools/nginx-1.10.1/logs/info.log info; 
  16.  
  17. #PID文件,记录当前启动的nginx的进程ID 
  18.  
  19. pid D:/Tools/nginx-1.10.1/logs/nginx.pid; 
  20.  
  21. #工作模式及连接数上限 
  22.  
  23. events { 
  24.  
  25. worker_connections 1024; #单个后台worker process进程的最大并发链接数 
  26.  
  27.  
  28. #设定http服务器,利用它的反向代理功能提供负载均衡支持 
  29.  
  30. http { 
  31.  
  32. #设定mime类型(邮件支持类型),类型由mime.types文件定义 
  33.  
  34. include D:/Tools/nginx-1.10.1/conf/mime.types; 
  35.  
  36. default_type application/octet-stream; 
  37.  
  38. #设定日志 
  39.  
  40. log_format main '[$remote_addr] - [$remote_user] [$time_local] "$request" ' 
  41.  
  42. '$status $body_bytes_sent "$http_referer" ' 
  43.  
  44. '"$http_user_agent" "$http_x_forwarded_for"'
  45.  
  46. access_log D:/Tools/nginx-1.10.1/logs/access.log main; 
  47.  
  48. rewrite_log on; 
  49.  
  50. #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用, 
  51.  
  52. #必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime. 
  53.  
  54. sendfile on; 
  55.  
  56. #tcp_nopush on; 
  57.  
  58. #连接超时时间 
  59.  
  60. keepalive_timeout 120
  61.  
  62. tcp_nodelay on; 
  63.  
  64. #gzip压缩开关 
  65.  
  66. #gzip on; 
  67.  
  68. #设定实际的服务器列表 
  69.  
  70. upstream zp_server1{ 
  71.  
  72. server 127.0.0.1:8089
  73.  
  74.  
  75. #HTTP服务器 
  76.  
  77. server { 
  78.  
  79. #监听80端口,80端口是知名端口号,用于HTTP协议 
  80.  
  81. listen 80
  82.  
  83. #定义使用www.xx.com访问 
  84.  
  85. server_name www.helloworld.com; 
  86.  
  87. #首页 
  88.  
  89. index index.html 
  90.  
  91. #指向webapp的目录 
  92.  
  93. root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp; 
  94.  
  95. #编码格式 
  96.  
  97. charset utf-8
  98.  
  99. #代理配置参数 
  100.  
  101. proxy_connect_timeout 180
  102.  
  103. proxy_send_timeout 180
  104.  
  105. proxy_read_timeout 180
  106.  
  107. proxy_set_header Host $host; 
  108.  
  109. proxy_set_header X-Forwarder-For $remote_addr; 
  110.  
  111. #反向代理的路径(和upstream绑定),location 后面设置映射的路径 
  112.  
  113. location / { 
  114.  
  115. proxy_pass http://zp_server1; 
  116.  
  117.  
  118. #静态文件,nginx自己处理 
  119.  
  120. location ~ ^/(images|javascript|js|css|flash|media|static)/ { 
  121.  
  122. root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views; 
  123.  
  124. #过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。 
  125.  
  126. expires 30d; 
  127.  
  128.  
  129. #设定查看Nginx状态的地址 
  130.  
  131. location /NginxStatus { 
  132.  
  133. stub_status on; 
  134.  
  135. access_log on; 
  136.  
  137. auth_basic "NginxStatus"
  138.  
  139. auth_basic_user_file conf/htpasswd; 
  140.  
  141.  
  142. #禁止访问 .htxxx 文件 
  143.  
  144. location ~ /\.ht { 
  145.  
  146. deny all; 
  147.  
  148.  
  149. #错误处理页面(可选择性配置) 
  150.  
  151. #error_page 404 /404.html; 
  152.  
  153. #error_page 500 502 503 504 /50x.html; 
  154.  
  155. #location = /50x.html { 
  156.  
  157. # root html; 
  158.  
  159. #} 
  160.  
  161.  
  162.  
  163. 好了,让我们来试试吧: 
  164.  
  165. 启动 webapp,注意启动绑定的端 

好了,让我们来试试吧:

启动 webapp,注意启动绑定的端口要和 nginx 中的 upstream 设置的端口保持一致。

更改 host:在 C:\Windows\System32\drivers\etc 目录下的 host 文件中添加一条 DNS 记录

  1. 127.0.0.1 www.helloworld.com 

启动前文中 startup.bat 的命令

在浏览器中访问 www.helloworld.com,不出意外,已经可以访问了。

负载均衡配置

上一个例子中,代理仅仅指向一个服务器。

但是,网站在实际运营过程中,多半都是有多台服务器运行着同样的 app,这时需要使用负载均衡来分流。

nginx 也可以实现简单的负载均衡功能。

假设这样一个应用场景:将应用部署在 192.168.1.11:80、192.168.1.12:80、192.168.1.13:80 三台 linux 环境的服务器上。网站域名叫 www.helloworld.com,公网 IP 为 192.168.1.11。在公网 IP 所在的服务器上部署 nginx,对所有请求做负载均衡处理。

nginx.conf 配置如下:

  1. http { 
  2.  
  3. #设定mime类型,类型由mime.type文件定义 
  4.  
  5. include /etc/nginx/mime.types; 
  6.  
  7. default_type application/octet-stream; 
  8.  
  9. #设定日志格式 
  10.  
  11. access_log /var/log/nginx/access.log; 
  12.  
  13. #设定负载均衡的服务器列表 
  14.  
  15. upstream load_balance_server { 
  16.  
  17. #weigth参数表示权值,权值越高被分配到的几率越大 
  18.  
  19. server 192.168.1.11:80 weight=5
  20.  
  21. server 192.168.1.12:80 weight=1
  22.  
  23. server 192.168.1.13:80 weight=6
  24.  
  25.  
  26. #HTTP服务器 
  27.  
  28. server { 
  29.  
  30. #侦听80端口 
  31.  
  32. listen 80
  33.  
  34. #定义使用www.xx.com访问 
  35.  
  36. server_name www.helloworld.com; 
  37.  
  38. #对所有请求进行负载均衡请求 
  39.  
  40. location / { 
  41.  
  42. root /root; #定义服务器的默认网站根目录位置 
  43.  
  44. index index.html index.htm; #定义首页索引文件的名称 
  45.  
  46. proxy_pass http://load_balance_server ;#请求转向load_balance_server 定义的服务器列表 
  47.  
  48. #以下是一些反向代理的配置(可选择性配置) 
  49.  
  50. #proxy_redirect off; 
  51.  
  52. proxy_set_header Host $host; 
  53.  
  54. proxy_set_header X-Real-IP $remote_addr; 
  55.  
  56. #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP 
  57.  
  58. proxy_set_header X-Forwarded-For $remote_addr; 
  59.  
  60. proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时) 
  61.  
  62. proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时) 
  63.  
  64. proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时) 
  65.  
  66. proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小 
  67.  
  68. proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置 
  69.  
  70. proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2) 
  71.  
  72. proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传 
  73.  
  74. client_max_body_size 10m; #允许客户端请求的最大单文件字节数 
  75.  
  76. client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数 
  77.  
  78.  
  79.  

网站有多个 webapp 的配置

当一个网站功能越来越丰富时,往往需要将一些功能相对独立的模块剥离出来,独立维护。这样的话,通常,会有多个 webapp。

举个例子:假如 www.helloworld.com 站点有好几个

webapp,finance(金融)、product(产品)、admin(用户中心)。访问这些应用的方式通过上下文(context)来进行区分:

  • www.helloworld.com/finance/
  • www.helloworld.com/product/
  • www.helloworld.com/admin/

我们知道,http 的默认端口号是 80,如果在一台服务器上同时启动这 3 个 webapp 应用,都用 80 端口,肯定是不成的。所以,这三个应用需要分别绑定不同的端口号。

那么,问题来了,用户在实际访问 www.helloworld.com 站点时,访问不同 webapp,总不会还带着对应的端口号去访问吧。所以,你再次需要用到反向代理来做处理。

配置也不难,来看看怎么做吧:

  1. http { 
  2.  
  3. #此处省略一些基本配置 
  4.  
  5. upstream product_server{ 
  6.  
  7. server www.helloworld.com:8081
  8.  
  9.  
  10. upstream admin_server{ 
  11.  
  12. server www.helloworld.com:8082
  13.  
  14.  
  15. upstream finance_server{ 
  16.  
  17. server www.helloworld.com:8083
  18.  
  19.  
  20. server { 
  21.  
  22. #此处省略一些基本配置 
  23.  
  24. #默认指向product的server 
  25.  
  26. location / { 
  27.  
  28. proxy_pass http://product_server; 
  29.  
  30.  
  31. location /product/{ 
  32.  
  33. proxy_pass http://product_server; 
  34.  
  35.  
  36. location /admin/ { 
  37.  
  38. proxy_pass http://admin_server; 
  39.  
  40.  
  41. location /finance/ { 
  42.  
  43. proxy_pass http://finance_server; 
  44.  
  45.  
  46.  

https 反向代理配置

一些对安全性要求比较高的站点,可能会使用 HTTPS(一种使用 ssl 通信标准的安全 HTTP 协议)。

这里不科普 HTTP 协议和 SSL 标准。但是,使用 nginx 配置 https 需要知道几点:

HTTPS 的固定端口号是 443,不同于 HTTP 的 80 端口

SSL 标准需要引入安全证书,所以在 nginx.conf 中你需要指定证书和它对应的 key

其他和 http 反向代理基本一样,只是在 Server 部分配置有些不同。

  1. #HTTP服务器 
  2.  
  3. server { 
  4.  
  5. #监听443端口。443为知名端口号,主要用于HTTPS协议 
  6.  
  7. listen 443 ssl; 
  8.  
  9. #定义使用www.xx.com访问 
  10.  
  11. server_name www.helloworld.com; 
  12.  
  13. #ssl证书文件位置(常见证书文件格式为:crt/pem) 
  14.  
  15. ssl_certificate cert.pem; 
  16.  
  17. #ssl证书key位置 
  18.  
  19. ssl_certificate_key cert.key; 
  20.  
  21. #ssl配置参数(选择性配置) 
  22.  
  23. ssl_session_cache shared:SSL:1m; 
  24.  
  25. ssl_session_timeout 5m; 
  26.  
  27. #数字签名,此处使用MD5 
  28.  
  29. ssl_ciphers HIGH:!aNULL:!MD5; 
  30.  
  31. ssl_prefer_server_ciphers on; 
  32.  
  33. location / { 
  34.  
  35. root /root; 
  36.  
  37. index index.html index.htm; 
  38.  
  39.  

静态站点配置

有时候,我们需要配置静态站点(即 html 文件和一堆静态资源)。

举例来说:如果所有的静态资源都放在了 /app/dist 目录下,我们只需要在 nginx.conf 中指定首页以及这个站点的 host 即可。

配置如下:

  1. worker_processes 1
  2.  
  3. events { 
  4.  
  5. worker_connections 1024
  6.  
  7.  
  8. http { 
  9.  
  10. include mime.types; 
  11.  
  12. default_type application/octet-stream; 
  13.  
  14. sendfile on; 
  15.  
  16. keepalive_timeout 65
  17.  
  18. gzip on; 
  19.  
  20. gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png; 
  21.  
  22. gzip_vary on; 
  23.  
  24. server { 
  25.  
  26. listen 80
  27.  
  28. server_name static.zp.cn; 
  29.  
  30. location / { 
  31.  
  32. root /app/dist; 
  33.  
  34. index index.html; 
  35.  
  36. #转发任何请求到 index.html 
  37.  
  38.  
  39.  

然后,添加 HOST:

127.0.0.1 static.zp.cn

此时,在本地浏览器访问 static.zp.cn ,就可以访问静态站点了。

搭建文件服务器

有时候,团队需要归档一些数据或资料,那么文件服务器必不可少。使用 Nginx 可以非常快速便捷的搭建一个简易的文件服务。

Nginx 中的配置要点:

  • 将 autoindex 开启可以显示目录,默认不开启。
  • 将 autoindex_exact_size 开启可以显示文件的大小。
  • 将 autoindex_localtime 开启可以显示文件的修改时间。
  • root 用来设置开放为文件服务的根路径。
  • charset 设置为 charset utf-8,gbk;,可以避免中文乱码问题(windows
  • 服务器下设置后,依然乱码,本人暂时没有找到解决方法)。

一个最简化的配置如下:

  1. autoindex on;# 显示目录 
  2.  
  3. autoindex_exact_size on;# 显示文件大小 
  4.  
  5. autoindex_localtime on;# 显示文件时间 
  6.  
  7. server { 
  8.  
  9. charset utf-8,gbk; # windows 服务器下设置后,依然乱码,暂时无解 
  10.  
  11. listen 9050 default_server; 
  12.  
  13. listen [::]:9050 default_server; 
  14.  
  15. server_name _; 
  16.  
  17. root /share/fs; 
  18.  

跨域解决方案

web 领域开发中,经常采用前后端分离模式。这种模式下,前端和后端分别是独立的 web 应用程序,例如:后端是 Java 程序,前端是 React 或 Vue 应用。

各自独立的 web app 在互相访问时,势必存在跨域问题。解决跨域问题一般有两种思路:

1、CORS

在后端服务器设置 HTTP 响应头,把你需要运行访问的域名加入加入 Access-Control-Allow-Origin中。

2、jsonp

把后端根据请求,构造 json 数据,并返回,前端用 jsonp 跨域。

这两种思路,本文不展开讨论。

需要说明的是,nginx 根据第一种思路,也提供了一种解决跨域的解决方案。

举例:www.helloworld.com 网站是由一个前端 app ,一个后端 app 组成的。前端端口号为 9000, 后端端口号为 8080。

前端和后端如果使用 http 进行交互时,请求会被拒绝,因为存在跨域问题。来看看,nginx 是怎么解决的吧:

首先,在 enable-cors.conf 文件中设置 cors :

  1. # allow origin list 
  2.  
  3. set $ACAO '*'
  4.  
  5. # set single origin 
  6.  
  7. if ($http_origin ~* (www.helloworld.com)$) { 
  8.  
  9. set $ACAO $http_origin; 
  10.  
  11.  
  12. if ($cors = "trueget") { 
  13.  
  14. add_header 'Access-Control-Allow-Origin' "$http_origin"
  15.  
  16. add_header 'Access-Control-Allow-Credentials' 'true'
  17.  
  18. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'
  19.  
  20. add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'
  21.  
  22.  
  23. if ($request_method = 'OPTIONS') { 
  24.  
  25. set $cors "${cors}options"
  26.  
  27.  
  28. if ($request_method = 'GET') { 
  29.  
  30. set $cors "${cors}get"
  31.  
  32.  
  33. if ($request_method = 'POST') { 
  34.  
  35. set $cors "${cors}post"
  36.  

接下来,在你的服务器中 include enable-cors.conf 来引入跨域配置:

  1. # ---------------------------------------------------- 
  2.  
  3. # 此文件为项目 nginx 配置片段 
  4.  
  5. # 可以直接在 nginx config 中 include(推荐) 
  6.  
  7. # 或者 copy 到现有 nginx 中,自行配置 
  8.  
  9. # www.helloworld.com 域名需配合 dns hosts 进行配置 
  10.  
  11. # 其中,api 开启了 cors,需配合本目录下另一份配置文件 
  12.  
  13. # ---------------------------------------------------- 
  14.  
  15. upstream front_server{ 
  16.  
  17. server www.helloworld.com:9000
  18.  
  19.  
  20. upstream api_server{ 
  21.  
  22. server www.helloworld.com:8080
  23.  
  24.  
  25. server { 
  26.  
  27. listen 80
  28.  
  29. server_name www.helloworld.com; 
  30.  
  31. location ~ ^/api/ { 
  32.  
  33. include enable-cors.conf; 
  34.  
  35. proxy_pass http://api_server; 
  36.  
  37. rewrite "^/api/(.*)$" /$1 break
  38.  
  39.  
  40. location ~ ^/ { 
  41.  
  42. proxy_pass http://front_server; 
  43.  
  44.  

到此,就完成了。

https://github.com/dunwu/nginx-tutorial

 

责任编辑:张燕妮 来源: 高效运维
相关推荐

2023-01-03 08:32:38

2020-07-13 15:10:47

Python代码字符串

2010-10-17 14:30:20

业务分析与优化云计算物联网

2023-05-08 11:57:24

索引数据库IO

2018-11-21 15:40:08

HTTP协议前端

2018-01-03 14:32:32

2017-10-16 00:57:23

单元测试代码覆盖

2023-08-27 21:22:02

Redis数据类

2022-07-29 07:48:15

HTTP常用状态码

2016-12-06 10:07:01

锐捷网络

2014-05-04 13:47:39

锐捷网络极简网络

2022-02-18 11:51:36

Python代码编程语言

2016-12-28 10:00:03

锐捷网络

2020-08-17 10:50:29

Python代码get

2018-05-22 09:47:07

2011-05-17 15:24:18

Shibboleth认证

2015-09-25 10:39:16

大数据工具应用场景

2018-08-17 16:13:52

大数据工具分析

2017-01-22 16:25:01

大数据软件工具应用场景

2022-07-11 14:23:09

加密货币比特币以太坊
点赞
收藏

51CTO技术栈公众号