背景
Nginx是一款轻量级的网页服务器、反向代理服务器.相较于Apache、lighttpd具有占有内存少,稳定性高等优势.它最常的用途是提供反向代理服务.
安装依赖
yum -y install gcc gcc-c++ autoconf automake make
nginx 中gzip模块需要 zlib 库,rewrite模块需要 pcre 库,ssl 功能需要openssl库
安装PCRE
1 | cd ~/source-module |
安装zlib
1 | cd ~/source-module |
安装ssl
1 | cd /usr/local |
安装nginx
下载源码并安装
1 | wget https://nginx.org/download/nginx-1.12.1.tar.gz |
在已运行的nginx上添加扩展模块
注: 该部分文章, 与上面文章不在一台机器上操作, 注意路径即可.
下面以添加fastdfs-nginx-module
模块为例进行操作.
查看当前已安装模块
1 | [root@Node nginx-1.12.1]# nginx -V |
1 | cd ~/workspaces/github |
注: 切记不要执行make install
指令, 否则将覆盖之前的配置文件
接下来切换到nginx
安装目录, 备份可执行的二进制文件, 复制./objs
目录下的对应文件到安装目录即可, 如下:
1 | cd /root/devTools/nginx-1.12.1/ |
查看
1 | [root@Node nginx-1.12.1]# nginx -V |
指令
将安装后的目录加入PATH中, 方便调用指令
编辑.bash_profile
文件
1 | export NGINX_HOME=/Users/ac/devTools/nginx-1.12.1 |
更新profile文件, source ~/.bash_profile
- 查看版本: nginx -v
- 检查配置文件是否正常: nginx -t
- 启动: nginx
- 重启: nginx -s reload
- 停止: nginx -s stop
- 强制停止: pkill nginx
注: 若提示Permission denied, 请在命令前添加sudo或切换到root用户(使用su命令)
配置
配置文件位置
1 | /Users/ac/devTools/nginx-1.12.1/conf/nginx.conf |
Nginx配置文件常见结构的从外到内依次是「http」「server」「location」等等,缺省的继承关系是从外到内,也就是说内层块会自动获取外层块的值作为缺省值.
server
1 | server { |
建议有多个server时, 将各server独立放入一个*.conf
文件中(例如: gyenno.conf), 并在nginx.conf文件内容末尾加入如下语句include conf.d/*.conf;
location
每个 url 请求都会对应的一个服务,nginx 进行处理转发或者是本地的一个文件路径,或者是其他服务器的一个服务路径.而这个路径的匹配是通过 location 来进行的.我们可以将 server 当做对应一个域名进行的配置,而 location 是在一个域名下对更精细的路径进行配置.
以上面的例子,可以将root和index指令放到一个location中,那么只有在匹配到这个location时才会访问root后的内容:
1 | location / { |
location 匹配规则
1 | ~ 波浪线表示执行一个正则匹配,区分大小写 |
匹配示例:
1 | location = / { |
静态文件映射
root
和alias
两个指令指定文件目录
autoindex on: 列出指定目录下的文件
root
1 | location /b/ { |
文件所在目录: root + location
例如: http://localhost/b/index.html, index.html所在目录为/a/b/
注: root后的/
可以省略
alias
1 | location /b/ { |
文件所在目录: alias
例如: http://localhost/b/index.html, index.html所在目录为/a/
注: root后的/
不可省略
转发
1 | location / { |
所有访问ts.gyenno.com
的请求都转发到本地机器的8080
端口.
负载均衡
1 | upstream myserver { |
我们在 upstream 中指定了一组机器,并将这个组命名为 myserver,这样在 proxypass 中只要将请求转移到 myserver 这个 upstream 中我们就实现了在四台机器的反向代理加负载均衡.其中的 ip_hash 指明了我们均衡的方式是按照用户的 ip 地址进行分配.另外还有轮询、指定权重轮询、fair、url_hash几种调度算法.
总结
以上是最简单的通过 nginx 实现静态文件转发、反向代理和负载均衡的配置.在 nginx 中所有的功能都是通过模块来实现的,比如当我们配置 upstream 时是用 upstream 模块,而 server 和 location 是在 http core 模块,其他的还有流控的 limt 模块,邮件的 mail 模块,https 的 ssl 模块.他们的配置都是类似的可以再 nginx的模块文档中找到详细的配置说明.