1.1Nginx 简介
Nginx (engine x) 是一个轻量级的、高性能的、基于 Http 的、反向代理服务器,静态 web
服务器。
Nginx 最初是由俄罗斯人 Igor Sysoev(伊戈尔·赛索耶夫)使用 C 语言为俄罗斯访问量第二的Rambler.ru 站点开发的一款服务器。2004 年 10 月发布第一个版本。
Nginx 的官网: http://nginx.org
国内大型的站点,例如百度、京东、新浪、网易、腾讯、淘宝等,都使用了 Nginx。https://www.netcraft.com/
1.2代理服务器
1.2.1正向代理
(1)隐藏

(2)翻墙

(3)提速

(4)缓存

(5)授权

1.2.2反向代理
(1)保护隐藏

(2)分布式路由

(3)负载均衡

(4)动静分离

(5)数据缓存

1.2.3正向代理与反向代理的区别
客户端是否清楚自己所要访问的服务器是谁;架设的位置不同
1.3Nginx 的特点
1.3.1高并发
一个Nginx 服务器在不做任何配置的情况下并发量可达 1000 左右。在硬件条件允许的前提下,Nginx 可以支持高达 5-10 万的并发量(除了 Nginx 的设置外,Linux 主机需要做大量的设置来配合Nginx)。
对比一下 Tomcat。Tomcat 服务器默认的并发量为 150(不做任何配置)。即,当有超过150 个用户同时访问某 Servlet 时,Tomcat 的响应就会变得非常慢。
1.3.2低消耗
官方给出的测试结果,10000 个非活跃连接,在Nginx 中仅消耗 2.5M 内存。对于一般性的 DoS 攻击来说就不是事儿,但对于 DDoS 也会是问题。
1.3.3热部署
可以在 7*24 小时不间断服务的前提下,进行 Nginx 版本的平滑升级,Nginx 配置文件的平滑修改。即在不停机的情况下升级 Nginx,修改替换 Nginx 配置文件。
1.3.4高可用
Nginx 只所以可以实现高并发,是因为其具有很多工作进程 worker。当这些工作进程中的某些出现问题停止工作时,并不会影响整个系统的整体运行。因为其它 worker 会接替那些出问题的线程。
1.3.5高扩展
Nginx 只所以现在的用户很多,是因为很多功能都已经开发好并模块化。若需要哪些功能,只需要安装相应功能的扩展模块即可。根据编写扩展模块所使用的语言的不同,可以划分为两类:C 语言扩展模块与 LUA 脚本扩展模块。 http://openresty.org/cn/
1.4Nginx 的下载与安装
1.4.1Nginx 的下载
nginx 的官网为:http://nginx.org。
1.4.2Nginx 的源码安装
(1)安装 Nginx
A、上传 Nginx
将下载好的 Nginx 上传到新复制的主机的/usr/tools 目录。
B、 安装 gcc
由于Nginx 是由 C/C++语言编写的,所以对其进行编译就必须要使用相关编译器。对于C/C++语言的编译器,使用最多的是 gcc 与 gcc-c++,而这两款编译器在 CentOS7 中是没有安装的,所以首先要安装这两款编译器。

C、 安装依赖库
基本的 Nginx 功能依赖于一些基本的库,在安装 Nginx 之前需要提前安装这些库。

D、创建解压目录
在/usr 下创建 apps 目录,用于存放解压后的安装包程序。

E、 解压 Nginx
将 Nginx 解压到/usr/apps 目录中。

进入到/usr/apps 目录中的Nginx 解压包目录,查看Nginx 的目录。

F、 生成 makefile
在 Nginx 解压目录下运行 make 命令,用于完成编译。但此时会给出提示:没有指定目标,并且没有发现编译文件 makefile。

编译命令 make 需要根据编译文件 makefile 进行编译,所以在编译之前需要先生成编译文件 makefile。使用 configure 命令可以生成该文件。
G、编译安装

(2)使 nginx 命令随处可用
在 Nginx 的安装目录/usr/local/nginx 中有一个 sbin 目录,其中存放着 nginx 的命令程序nginx。

1.4.3Nginx 命令
(1)查看命令选项nginx -h
使用 nginx –h 可以查看 Nginx 命令的选项。

(2)相看 Nginx 版本信息 nginx –v 或-V
nginx –v:显示 Nginx 版本信息。

nginx –V:显示更多的版本相关信息,例如 gcc 的版本,OpenSSL 的版本等。

(3)测试配置文件命令nginx -tq
nginx –t:测试配置文件是否正确,默认只测试默认的配置文件 conf/nginx.conf。nginx –T:测试配置文件是否正确,并显示配置文件内容。
nginx –tq:在配置文件测试过程中,禁止显示非错误信息,即只显示错误信息。

可以结合-c 选项指定要测试的配置文件。注意,其不会启动 nginx。

(4)停止命令nginx –s stop/quit
在 nginx 命令后通过-s 选项,可以指定不同的信号完成不同的功能。
nginx –s stop:强制停止Nginx,无论当前工作进程是否正在处理工作。
nginx –s quit:优雅停止 Nginx,使当前的工作进程完成当前工作后停止。

(5)平滑重启命令nginx –s reload
在不重启Nginx 的前提下重新加载Nginx 配置文件,称为平滑重启。

(6)nginx –s reopen
重新打开日志文件。
(7)nginx –p
指定Nginx 配置文件的存放路径。
(8)启动命令nginx –c file
nginx –c(小写字母)可启动 Nginx,启动成功后无任何提示。

若不指定配置文件,则默认加载的是 Nginx 安装目录下的 conf/nginx.cnf。

(9)nginx –g
设置配置文件以外的全局指令。
1.4.4页面访问测试
(1)关闭防火墙

(2)浏览器访问
由于Nginx 服务器默认的端口号为 80,所以在浏览器中直接输入 Nginx 的主机名或 IP, 就可以看到 Nginx 欢迎页面。只要可以看到以下页面信息,则说明 Nginx 安装运行成功。

网友评论