超实用的 Nginx 极简教程,覆盖了常用场景
概述
什么是 Nginx?
Nginx (engine x) 是一款轻量级的 Web 服务器 、反向署理服务器及电子邮件(IMAP/POP3)署理服务器。
什么是反向署理?
反向署理(Reverse Proxy)方法是指以署理服务器来接受 internet 上的衔接恳求,然后将恳求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上恳求衔接的客户端,此时署理服务器对外就表现为一个反向署理服务器。
装置与运用
装置
具体装置方法请参阅:Nginx 装置
运用
nginx 的运用比较简单,便是几条指令。
常用到的指令如下:
nginx -s stop 快速封闭Nginx,或许不保存相关信息,并敏捷终止web服务。 nginx -s quit 平稳封闭Nginx,保存相关信息,有安排的结束web服务。 nginx -s reload 因改变了Nginx相关装备,需求从头加载装备而重载。 nginx -s reopen 从头打开日志文件。 nginx -c filename 为 Nginx 指定一个装备文件,来代替缺省的。 nginx -t 不运转,而只是测验装备文件。nginx 将查看装备文件的语法的正确性,并尝试打开装备文件中所引用到的文件。 nginx -v 显现 nginx 的版别。 nginx -V 显现 nginx 的版别,编译器版别和装备参数。
假设不想每次都敲指令,能够在 nginx 装置目录下新添一个发动批处理文件startup.bat ,双击即可运转。内容如下:
@echo off rem 假设发动前现已发动nginx并记载下pid文件,会kill指定进程 nginx.exe -s stop rem 测验装备文件语法正确性 nginx.exe -t -c conf/nginx.conf rem 显现版别信息 nginx.exe -v rem 按照指定装备去发动nginx nginx.exe -c conf/nginx.conf
假设是运转在 Linux 下,写一个 shell 脚本,迥然不同。
nginx 装备实战
我始终认为,各种开发工具的装备还是结合实战来讲述,会让人更易了解。
http 反向署理装备
我们先完成一个小方针:不考虑复杂的装备,只是是完成一个 http 反向署理。
nginx.conf 装备文件如下:注:conf / nginx.conf 是 nginx 的默许装备文件。你也能够运用 nginx -c 指定你的装备文件
#运转用户 #user somebody; #发动进程,一般设置成和cpu的数量相等 worker_processes 1; #全局错误日志 error_log D:/Tools/nginx-1.10.1/logs/error.log; error_log D:/Tools/nginx-1.10.1/logs/notice.log notice; error_log D:/Tools/nginx-1.10.1/logs/info.log info; #PID文件,记载当前发动的nginx的进程ID pid D:/Tools/nginx-1.10.1/logs/nginx.pid; #工作形式及衔接数上限 events { worker_connections 1024; #单个后台worker process进程的最大并发链接数 } #设定http服务器,利用它的反向署理功用供给负载均衡支撑 http { #设定mime类型(邮件支撑类型),类型由mime.types文件界说 include D:/Tools/nginx-1.10.1/conf/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 D:/Tools/nginx-1.10.1/logs/access.log main; rewrite_log on; #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方法)来输出文件,关于一般运用, #有必要设为 on,假设用来进行下载等运用磁盘IO重负载运用,可设置为 off,以平衡磁盘与网络I/O处理速度,下降体系的uptime. sendfile on; #tcp_nopush on; #衔接超时时刻 keepalive_timeout 120; tcp_nodelay on; #gzip紧缩开关 #gzip on; #设定实践的服务器列表 upstream zp_server1{ server 127.0.0.1:8089; } #HTTP服务器 server { #监听80端口,80端口是闻名端口号,用于HTTP协议 listen 80; #界说运用www.xx.com拜访 server_name www.helloworld.com; #主页 index index.html #指向webapp的目录 root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp; #编码格局 charset utf-8; #署理装备参数 proxy_connect_timeout 180; proxy_send_timeout 180; proxy_read_timeout 180; proxy_set_header Host $host; proxy_set_header X-Forwarder-For $remote_addr; #反向署理的途径(和upstream绑定),location 后边设置映射的途径 location / { proxy_pass http://zp_server1; } #静态文件,nginx自己处理 location ~ ^/(images|javascript|js|css|flash|media|static)/ { root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views; #过期30天,静态文件不怎样更新,过期能够设大一点,假设频频更新,则能够设置得小一点。 expires 30d; } #设定查看Nginx状态的地址 location /NginxStatus { stub_status on; access_log on; auth_basic "NginxStatus"; auth_basic_user_file conf/htpasswd; } #制止拜访 .htxxx 文件 location ~ /\.ht { deny all; } #错误处理页面(可选择性装备) #error_page 404 /404.html; #error_page 500 502 503 504 /50x.html; #location = /50x.html { # root html; #} } }
好了,让我们来试试吧:
- 发动 webapp,注意发动绑定的端口要和 nginx 中的upstream设置的端口保持一致。
- 更改 host:在 C:\Windows\System32\drivers\etc 目录下的 host 文件中增加一条 DNS 记载
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 装备如下:
http { #设定mime类型,类型由mime.type文件界说 include /etc/nginx/mime.types; default_type application/octet-stream; #设定日志格局 access_log /var/log/nginx/access.log; #设定负载均衡的服务器列表 upstream load_balance_server { #weigth参数表明权值,权值越高被分配到的几率越大 server 192.168.1.11:80 weight=5; server 192.168.1.12:80 weight=1; server 192.168.1.13:80 weight=6; } #HTTP服务器 server { #侦听80端口 listen 80; #界说运用www.xx.com拜访 server_name www.helloworld.com; #对一切恳求进行负载均衡恳求 location / { root /root; #界说服务器的默许网站根目录方位 index index.html index.htm; #界说主页索引文件的称号 proxy_pass http://load_balance_server ;#恳求转向load_balance_server 界说的服务器列表 #以下是一些反向署理的装备(可选择性装备) #proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; #后端的Web服务器能够通过X-Forwarded-For获取用户实在IP proxy_set_header X-Forwarded-For $remote_addr; proxy_connect_timeout 90; #nginx跟后端服务器衔接超时时刻(署理衔接超时) proxy_send_timeout 90; #后端服务器数据回传时刻(署理发送超时) proxy_read_timeout 90; #衔接成功后,后端服务器呼应时刻(署理接收超时) proxy_buffer_size 4k; #设置署理服务器(nginx)保存用户头信息的缓冲区巨细 proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置 proxy_busy_buffers_size 64k; #高负荷下缓冲巨细(proxy_buffers*2) proxy_temp_file_write_size 64k; #设定缓存文件夹巨细,大于这个值,将从upstream服务器传 client_max_body_size 10m; #允许客户端恳求的最大单文件字节数 client_body_buffer_size 128k; #缓冲区署理缓冲用户端恳求的最大字节数 } } }
网站有多个 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,总不会还带着对应的端口号去拜访吧。所以,你再次需求用到反向署理来做处理。
装备也不难,来看看怎样做吧:
http { #此处省掉一些根本装备 upstream product_server{ server www.helloworld.com:8081; } upstream admin_server{ server www.helloworld.com:8082; } upstream finance_server{ server www.helloworld.com:8083; } server { #此处省掉一些根本装备 #默许指向product的server location / { proxy_pass http://product_server; } location /product/{ proxy_pass http://product_server; } location /admin/ { proxy_pass http://admin_server; } location /finance/ { proxy_pass http://finance_server; } } }
https 反向署理装备
一些对安全性要求比较高的站点,或许会运用 HTTPS(一种运用 ssl 通讯规范的安全 HTTP 协议)。
这里不科普 HTTP 协议和 SSL 规范。可是,运用 nginx 装备 https 需求知道几点:
- HTTPS 的固定端口号是 443,不同于 HTTP 的 80 端口
- SSL 规范需求引进安全证书,所以在 nginx.conf 中你需求指定证书和它对应的 key
其他和 http 反向署理根本一样,只是在Server部分装备有些不同。
#HTTP服务器 server { #监听443端口。443为闻名端口号,首要用于HTTPS协议 listen 443 ssl; #界说运用www.xx.com拜访 server_name www.helloworld.com; #ssl证书文件方位(常见证书文件格局为:crt/pem) ssl_certificate cert.pem; #ssl证书key方位 ssl_certificate_key cert.key; #ssl装备参数(选择性装备) ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; #数字签名,此处运用MD5 ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root /root; index index.html index.htm; } }
静态站点装备
有时候,我们需求装备静态站点(即 html 文件和一堆静态资源)。
举例来说:假设一切的静态资源都放在了/app/dist目录下,我们只需求在nginx.conf中指定主页以及这个站点的 host 即可。
装备如下:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; gzip on; gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png; gzip_vary on; server { listen 80; server_name static.zp.cn; location / { root /app/dist; index index.html; #转发任何恳求到 index.html } } }
然后,增加 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 服务器下设置后,仍然乱码,自己暂时没有找到处理方法)。
一个最简化的装备如下:
autoindex on;# 显现目录 autoindex_exact_size on;# 显现文件巨细 autoindex_localtime on;# 显现文件时刻 server { charset utf-8,gbk; # windows 服务器下设置后,仍然乱码,暂时无解 listen 9050 default_server; listen [::]:9050 default_server; server_name _; root /share/fs; }
跨域处理方案
web 领域开发中,常常采用前后端别离形式。这种形式下,前端和后端分别是独立的 web 运用程序,例如:后端是 Java 程序,前端是 React 或 Vue 运用。
各自独立的 web app 在互相拜访时,势必存在跨域问题。处理跨域问题一般有两种思路:
- CORS
在后端服务器设置 HTTP 呼应头,把你需求运转拜访的域名参加参加Access-Control-Allow-Origin中。
- jsonp
把后端依据恳求,结构 json 数据,并返回,前端用 jsonp 跨域。
这两种思路,本文不展开讨论。
需求阐明的是,nginx 依据第一种思路,也供给了一种处理跨域的处理方案。
举例:www.helloworld.com 网站是由一个前端 app ,一个后端 app 组成的。前端端口号为 9000, 后端端口号为 8080。
前端和后端假设运用 http 进行交互时,恳求会被回绝,因为存在跨域问题。来看看,nginx 是怎样处理的吧:
首要,在 enable-cors.conf 文件中设置 cors :
# allow origin list set $ACAO '*'; # set single origin if ($http_origin ~* (www.helloworld.com)$) { set $ACAO $http_origin; } if ($cors = "trueget") { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($request_method = 'OPTIONS') { set $cors "${cors}options"; } if ($request_method = 'GET') { set $cors "${cors}get"; } if ($request_method = 'POST') { set $cors "${cors}post"; }
接下来,在你的服务器中include enable-cors.conf来引进跨域装备:
# ---------------------------------------------------- # 此文件为项目 nginx 装备片段 # 能够直接在 nginx config 中 include(推荐) # 或者 copy 到现有 nginx 中,自行装备 # www.helloworld.com 域名需配合 dns hosts 进行装备 # 其中,api 敞开了 cors,需配合本目录下另一份装备文件 # ---------------------------------------------------- upstream front_server{ server www.helloworld.com:9000; } upstream api_server{ server www.helloworld.com:8080; } server { listen 80; server_name www.helloworld.com; location ~ ^/api/ { include enable-cors.conf; proxy_pass http://api_server; rewrite "^/api/(.*)$" /$1 break; } location ~ ^/ { proxy_pass http://front_server; } }
到此,就完成了。