Nginx概述与安装配置
一、Nginx 概述
Nginx (engine x)是一个高性能的HTTP 和反向代理服务器,也是一个IMAP/POP3/SMTP 服务器。
其特点是占有内存少,并发能力强
Nginx 可以作为静态页面的 web 服务器,同时还支持 CGI 协议的动态语言,比如 perl、php 等。但是不支持 java。
常用用途:正向代理和反向代理
一般情况下,如果没有特别说明,代理技术默认说的是正向代理技术。
正向代理: 正向代理(forward)是一个位于客户端【用户 A】和原始服务器(origin server)【服务器 B】之间的服务器【代理服务器 Z】,为了从原始服务器取得内容,用户 A 向代理服务器 Z 发送一个请求并指定目标(服务器 B),然后代理服务器 Z 向服务器 B 转交请求并将获得的内容返回给客户端。客户端必须要进行一些特别的设置才能使用正向代理。(类似于跳板)
从图上来看:正向代理就是代理服务器替代访问方【用户 A】去访问目标服务器【服务器 B】
反向代理:服务器位于用户与目标服务器之间,但是对于用户而言,反向代理服务器就相当于目标服务器,即用户直接访问反向代理服务器就可以获得目标服务器的资源。同时,用户不需要知道目标服务器的地址,也无须在用户端作任何设定。反向代理服务器通常可用来作为 Web 加速,即使用反向代理作为 Web 服务器的前置机来降低网络和服务器的负载,提高访问效率
二、Nginx 安装
官方网站:http://nginx.org/
Nginx 在 linux 下安装,环境 CentOS7
1、安装所需插件
① 安装 gcc
gcc 是 linux 下的编译器,查看版本
1 | gcc -v |
没有安装的话:
1 | yum -y install gcc gcc-c++ |
②pcre、pcre-devel 安装
pcre 是一个 perl 库,包括 perl 兼容的正则表达式库,因为 nginx 的 http 模块使用 pcre 来解析正则表达式,所以需要安装 pcre 库
1 | yum install -y pcre pcre-devel |
③zlib 安装
zlib 库提供了很多种压缩和解压缩方式,而 nginx 使用 zlib 对 http 包的内容进行 gzip,所以需要安装
1 | yum install -y zlib zlib-devel |
④ 安装 OpenSSL
OpenSSL 是 web 安全通信的基石,OpenSSL 是一个开放源代码的软件库包,应用程序可以使用这个包来进行安全通信,避免窃听,同时确认另一端连接者的身份。这个包广泛被应用在互联网的网页服务器上
1 | yum install -y openssl openssl-devel |
⑤ 一键安装
1 | yum install -y gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel |
2、安装 nginx
① 下载 nginx 安装包
查看或者下载最新版的 nginx:点我查看
1 | wget http://nginx.org/download/nginx-1.21.0.tar.gz |
② 压缩包解压
解压到当前目录
1 | tar -zxvf nginx-1.21.0.tar.gz |
③ 安装
源码的安装一般由 3 个步骤组成:配置(configure)、编译(make)、安装(make install)
configure 文件是一个可执行的脚本文件,有很多选项,在待安装的源码目录下使用命令./configure –help 可以输出详细的选项列表
其中–prefix 选项是配置安装目录,如果不配置该选项,安装后可执行文件默认放在
/usr /local/bin
,库文件默认放在/usr/local/lib
,配置文件默认放在/usr/local/etc
,其它的资源文件放在/usr /local/share
进入安装目录
1 | cd nginx-1.21.0 |
执行安装
1 | ./configure --prefix=/usr/local/nginx --with-http_ssl_module |
–with-http_ssl_module:ssl 模块
④ 关闭防火墙
在 windows 系统中访问 linux 中 nginx,默认不能访问的,因为防火墙问题
关闭防火墙-开放访问的端口号,80 端口
查看防火墙状态
1 | systemctl status firewalld |
查看开放的端口号
1 | firewall-cmd --list-all |
设置开放的服务或端口号
1 | firewall-cmd --add-service=http --permanent |
重启防火墙
1 | firewall-cmd --reload |
⑤ 启动 nginx 服务
切换到上面的 nginx 安装目录 sbin 文件夹内
1 | cd /usr/local/nginx/sbin |
启动 nginx
1 | ./nginx |
⑥ 查看启动状态
通过进程查询:
1 | ps -ef | grep nginx |
通过端口查询,nginx 默认是 80 端口
1 | lsof -i:80 |
⑦ 访问
本机访问
1 | curl 127.0.0.1 |
三、Nginx 配置与应用
1、nginx 相关命令
① 配置环境变量
如果自定义了部署路径,需要将部署的 sbin 路径配置在 : /etc/profile
文件的 环境变量中(PATH)
1 | vim /etc/profile |
在 profile 文件末尾,加上一行指向你的 nginx 的安装位置的 sbin 目录
1 | PATH=$PATH:/usr/local/nginx/sbin |
重新加载环境
1 | source /etc/profile |
②nginx 相关命令
验证配置是否正确
1 | nginx -t |
查看 Nginx 的版本号
1 | nginx -V |
启动 Nginx
1 | nginx |
不停止服务,更新 nginx 的配置文件
1 | nginx -s reload |
快速停止或关闭
1 | nginx -s stop |
正常停止或关闭
1 | nginx -s quit |
-s 代表的是向主进程发送信号。其中信号有 4 个,stop ,quit, reopen, reload。
2、Nginx 配置文件
Nginx 配置文件在 nginx/conf/nginx.conf
我的配置文件在/usr/local/nginx/conf
目录下
1 | vim /usr/local/nginx/conf/nginx.conf |
3、nginx 配置中文详解
1 | #配置worker进程运行用户 nobody也是一个linux用户,一般用于启动程序,没有密码 |