nginx学习笔记

原创千与千寻之前 最后发布于2019-04-29 21:09:50 阅读数 60 收藏
展开

新的测试
123
千与千寻之前
¥29.90
去订阅
¶一、简介
Nginx(“engine x”)是一款是由俄罗斯的程序设计师Igor Sysoev所开发高性能的 Web和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。

在高连接并发的情况下,Nginx是Apache服务器不错的替代品。

¶二、编译安装
官方下载地址:http://nginx.org/en/download.html

版本号是双数的是稳定版,而单数则是开发版。

以下以编译安装来讲述。为什么选择编译安装而不选择yum或者apt包管理器安装呢?因为yum或者apt安装的是已经编译好的二进制文件,而已经编译好就说明扩展模块已经固定,很难去添加或者修改自定义的扩展模块,这里选择编译安装就是为了解决这个问题。

¶1.准备活动
1
2
3
4
5
6
##下载
wget http://nginx.org/download/nginx-1.14.0.tar.gz
##解压
tar zxvf nginx-1.14.0.tar.gz
##设置vim编辑nginx配置文件语法高亮(可选,如果不想用了直接删除~/.vim/目录即可)
mkdir ~/.vim && cp -r nginx-1.14.0/contrib/vim/* ~/.vim/
¶2. 安装编译工具及依赖库文件
1
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel pcre pcre-devel
¶3.编译并安装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#进入解压好的源码目录
cd nginx-1.14.0

#生成MakeFile
./configure \
--prefix=/usr/local/nginx \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_sub_module \
--with-http_gzip_static_module

#根据MakeFile编译
make

#安装
make install
安装目录结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/usr/local/nginx
├── conf #存放配置文件
│   ├── fastcgi.conf
│   ├── fastcgi.conf.default
│   ├── fastcgi_params
│   ├── fastcgi_params.default
│   ├── koi-utf
│   ├── koi-win
│   ├── mime.types
│   ├── mime.types.default
│   ├── nginx.conf
│   ├── nginx.conf.default
│   ├── scgi_params
│   ├── scgi_params.default
│   ├── uwsgi_params
│   ├── uwsgi_params.default
│   └── win-utf
├── html #web基础根目录
│   ├── 50xhtml
│   └── index.html
├── logs #日志文件目录
└── sbin #执行脚本目录
└── nginx
¶三、常用命令
¶1. 启动
1
/usr/local/nginx/sbin/nginx
查看是否启动命令: ps aux | grep nginx

¶2. 停止
1
2
3
/usr/local/nginx/sbin/nginx -s stop
#或者
/usr/local/nginx/sbin/nginx -s quit
¶3. 重启
1
$ /usr/local/nginx/sbin/nginx -s reopen
¶4. 动态加载
1
/usr/local/nginx/sbin/nginx -s reload
区别:

nginx -s quit:此方式停止步骤是待nginx进程处理任务完毕进行停止。

nginx -s stop:此方式相当于先查出nginx进程id再使用kill命令强制杀掉进程。

nginx -s reload:动态加载,当配置文件nginx.conf有变化时执行该命令动态加载。

¶5. 测试配置文件正确性
1
/usr/local/nginx/sbin/nginx -t
¶6. 其他常用命令
1
2
#查看编译加载的模块
/usr/local/nginx/sbin/nginx -V
¶四、yum安装
1
sudo yum install yum-utils
设置官方yum源以能够使用最新版本

1
vim /etc/yum.repos.d/nginx.repo
1
2
3
4
5
6
7
8
9
10
11
12
13
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
yum安装

1
yum install nginx
安装好后可以查看一些详细信息

1
2
3
4
5
##查寻nginx
[root@IllinformedMaroon-VM ~]# rpm -q nginx
nginx-1.16.0-1.el7.ngx.x86_64
[root@IllinformedMaroon-VM ~]# nginx -v
nginx version: nginx/1.16.0
Nginx安装⽬目录

1
2
##查看安装目录
rpm -ql nginx
如下表格对 Nginx 安装⽬目录做详细概述

路路径 类型 作⽤
/etc/nginx
/etc/nginx/nginx.conf
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf 配置文件 Nginx主配置文件
/etc/nginx/fastcgi_params
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params 配置文件 Cgi、Fastcgi、Uwcgi配置文件
/etc/nginx/win-utf
/etc/nginx/koi-utf
/etc/nginx/koi-win 配置⽂文件 Nginx编码转换映射文件
/etc/nginx/mime.types 配置⽂文件 http协议的Content-Type与扩展名
/usr/lib/systemd/system/nginx.service 配置⽂件 配置系统守护进程管理器
/etc/logrotate.d/nginx 配置⽂件 Nginx⽇志轮询,⽇志切割
/usr/sbin/nginx
/usr/sbin/nginx-debug 命令 Nginx终端管理命令
/etc/nginx/modules
/usr/lib64/nginx
/usr/lib64/nginx/modules ⽬录 Nginx模块⽬录
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html ⽬录 Nginx默认站点⽬录
/usr/share/doc/nginx-1.12.2
/usr/share/man/man8/nginx.8.gz ⽬录 Nginx的缓存⽬录
/var/log/nginx ⽬录 Nginx的⽇志⽬录
Nginx编译参数

查看Nginx编译参数

1
nginx -V
下表展示了Nginx编译参数选项以及作⽤

编译选项 作⽤
–prefix=/etc/nginx
–sbin-path=/usr/sbin/nginx
–modules-path=/usr/lib64/nginx/modules
–conf-path=/etc/nginx/nginx.conf
–error-log-path=/var/log/nginx/error.log
–http-log-path=/var/log/nginx/access.log
–pid-path=/var/run/nginx.pid
–lock-path=/var/run/nginx.lock 程序安装⽬录和路径
–http-client-body-temp-path=/var/cache/nginx/clie
nt_tem
–http-proxy-temp-path=/var/cache/nginx/proxy_te
mp
–http-fastcgi-temp-path=/var/cache/nginx/fastcgi_
temp
–http-uwsgi-temp-path=/var/cache/nginx/uwsgi_te
mp
–http-scgi-temp-path=/var/cache/nginx/scgi_temp 临时缓存⽂件
–user=nginx
–group=nginx 设定Nginx进程启动⽤户和组(安全)
–with-cc-opt 设置额外的参数将被添加到CFLAGS变量
–with-ld-opt 设置附加的参数, 链接系统库
¶五、常⽤模块
Nginx模块分为 Nginx官⽅模块以及Nginx第三⽅模块

Nginx编译选项 模块作⽤
ngx_http_core_module 包含⼀些核⼼的http参数配置,对应Nginx的配置区块部分
ngx_http_access_module 访问控制模块,⽤来控制⽹站⽤户对Nginx的访问
ngx_http_gzip_module 压缩模块,对Nginx返回的数据压缩,属于性能优化模块
ngx_http_fastcgi_module fastci模块,和动态应⽤相关的模块,例如PHP
ngx_http_proxy_module proxy代理模块
ngx_http_upstream_modul 负载均衡模块,可以实现⽹站的负载均衡功能及节点的健康检查。
ngx_http_rewrite_module URL地址重写模块
ngx_http_limit_conn_modu 限制⽤户并发连接数及请求数模块
ngx_http_limit_req_module 限制Nginx request processing rate根据定义的key
ngx_http_log_module 访问⽇志模块,以指定的格式记录Nginx客户访问⽇志等信息
ngx_http_auth_basic_mod Web认证模块,设置Web⽤户通过账号密码访问Nginx
nginx_http_ssl_module ssl模块,⽤于加密的http连接,如https
¶六、内置变量
http核⼼模块的内置变量

http请求变量
Nginx内置变量
⾃定义变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$uri: 当前请求的uri,不带参数
$request_uri: 请求的uri,带完整参数
$host: http请求报⽂中host⾸部,如果没有则以处理此请求的虚拟主机的主机名代替
$hostname: nginx服务运⾏在主机的主机名
$remote_addr: 客户端IP
$remote_port: 客户端端⼝
$remote_user: 使⽤⽤户认证时客户端⽤户输⼊的⽤户名
$request_filename: ⽤户请求中的URI经过本地root或alias转换后映射的本地⽂件路径
$request_method: 请求⽅法, GET POST PUT
$server_addr: 服务器地址
$server_name: 服务器名称
$server_port: 服务器端⼝
$server_protocol: 服务器向客户端发送响应时的协议, 如http/1.1 http/1.0
$scheme:在请求中使⽤scheme, 如http://xxx.com中的http
$http_HEADER: 匹配请求报⽂中指定的HEADER
$http_host: 匹配请求报⽂中的host⾸部
$document_root: 当前请求映射到的root配置
¶七、动静分离
这里的静态资源用图片来表示,而动态资源用jsp来表示。

¶1. 环境准备(A主机和B主机)
上游服务主机(A主机)

ip:101.132.45.132

作用:提供静态资源和动态资源服务(nginx提供静态资源资源+tomcat提供动态资源)

代理主机(B主机)

ip:198.23.188.200:

作用:承担反向代理的角色(nginx实现反向代理)

¶2. A主机环境搭建
¶2.1 动态资源的准备
tomcat安装很傻瓜式,解压即用,这里就不详细介绍。

添加jsp到tomcat web根目录里

1
vim /usr/local/apache-tomcat-8.5.31/webapps/ROOT/java_test.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>JSP Test Page</title>
</head>
<body>
<%
Random rand = new Random();
out.println("<h2>Random number:</h2>");
out.println(rand.nextInt(99)+100);
%>
</body>
</html>
运行tomcat

1
sh /usr/local/apache-tomcat-8.5.31/bin/startup.sh
¶2.2 静态资源的准备
首先确保nginx主配置文件nginx.conf的http节点中有导入conf.d目录的配置文件。如下:

1
2
3
4
5
6
7
http {
...

include 你的nginx配置文件路径/conf.d/*.conf;

...
}
编辑nginx配置文件配置静态资源访问控制

1
vim conf.d/static.conf
1
2
3
4
5
6
7
8
server {
listen 80;
server_name 101.132.45.132;
#静态图片资源访问控制
location ~ .*\.(jpg|png|gif)$ {
root /usr/share/nginx/resource/img;
}
}
在/usr/share/nginx/resource/img目录里放一张logo.jpg的图片做测试,并且确保有访问权限

重新加载nginx配置

1
nginx -s reload
¶3. B主机环境搭建
首先确保nginx主配置文件nginx.conf的http节点中有导入conf.d目录的配置文件。如下:

1
2
3
4
5
6
7
http {
...

include 你的nginx配置文件路径/conf.d/*.conf;

...
}
配置反向代理调度策略

1
vim conf.d/dynamic_static_proxy.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#配置静态资源请求的地址和端口
upstream static {
server 101.132.45.132:80;
}

#配置动态资源请求的地址和端口
upstream dynamic_java {
server 101.132.45.132:8080;
}

#配置当前服务器的虚拟主机
server {
listen 80;
server_name 198.23.188.200;
location / {
root /usr/share/nginx/html;
index index.html;
}
location ~ .*\.(png|jpg|gif)$ {
#静态图片资源走代理路线
proxy_pass http://static;
include proxy_params; #也可以把/etc/nginx/proxy_params里的内容替换掉这一行

#静态图片资源直接走本地
#root /usr/share/nginx/resource/img;
}
location ~ .*\.jsp$ {
proxy_pass http://dynamic_java;
include proxy_params;
}
}
创建并配置代理参数文件

1
vim /etc/nginx/proxy_params
1
2
3
4
5
6
7
8
9
10
11
12
proxy_redirect default;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffer_size 32k;
proxy_buffering on;
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 256k;
重新加载nginx配置

1
nginx -s reload
¶4. 访问测试
在代理主机B主机上编写动静分离的页面做测试

1
vim /usr/share/nginx/html/dynamic_static.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>测试nginx动静分离</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://198.23.188.200/java_test.jsp",
success: function(data) {
$("#get_data").html(data)
},
error: function() {
alert("fail!!,请刷新再试!");
}
});
});
</script>

<body>
<h1 style="color: #0688e8;">测试动静分离</h1>

<h2>静态数据:</h2>
<img src="http://198.23.188.200/logo.jpg" height="200" width="200">
<h2>动态数据:</h2>
<div id="get_data"></div>
</body>
</html>
访问代理主机B主机的测试页面

到这里nginx配置动静分类的应用服务就完成了。

 

¶八、负载均衡
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
upstream ops_load {
#可为本地的虚拟主机,也可以为远程的其他vps上的nginx虚拟主机,默认是轮询的方式访问
server 198.23.188.200:8081;
server 198.23.188.200:8082;
server 198.23.188.200:8083;
server 144.34.145.10:8084;
server 101.132.45.132:80;
}

server{
listen 80;
server_name test.qcmoke.top;
index index.html;

location / {
proxy_pass http://ops_load;
}
}


#本地测试的虚拟主机节点
server {
listen 8081;
root /usr/share/nginx/load/node1;
index index.html;
}

server {
listen 8082;
root /usr/share/nginx/load/node2;
index index.html;
}

server {
listen 8083;
root /usr/share/nginx/load/node3;
index index.html;
}
¶九、配置https
这里以Let’ s Encrypt免费https CA证书为例。

¶1. 配置一个nginx站点
1
vim qcmoke.top.conf
1
2
3
4
5
6
7
server{
server_name qcmoke.top;
listen 80;
charset utf-8;
root /usr/share/nginx/html;
index index.html;
}
1
nginx -s reload
¶2. 安装certbot工具
1
2
yum install -y epel-release
yum install -y certbot
¶3. 申请证书
1
2
3
# 使用方法:certbot certonly --webroot -w [Web站点目录] -d [站点域名] -m [联系人email地址] --agree-tos
# 例如
certbot certonly --webroot -w /usr/share/nginx/html -d qcmoke.top -m qcmoke@gmail.com --agree-tos
完整过程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[root@IllinformedMaroon-VM conf.d]# certbot certonly --webroot -w /usr/share/nginx/html -d qcmoke.top -m qcmoke@gmail.com --agree-tos
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Starting new HTTPS connection (1): supporters.eff.org
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for qcmoke.top
Using the webroot path /usr/share/nginx/html for all unmatched domains.
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/qcmoke.top/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/qcmoke.top/privkey.pem
Your cert will expire on 2019-10-06. To obtain a new or tweaked
version of this certificate in the future, simply run certbot
again. To non-interactively renew *all* of your certificates, run
"certbot renew"
- Your account credentials have been saved in your Certbot
configuration directory at /etc/letsencrypt. You should make a
secure backup of this folder now. This configuration directory will
also contain certificates and private keys obtained by Certbot so
making regular backups of this folder is ideal.
- If you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le

[root@IllinformedMaroon-VM conf.d]#
证书的保存位置在/etc/letsencrypt/live/qcmoke.top/:

1
2
3
4
5
6
/etc/letsencrypt/live/qcmoke.top/
├── cert.pem -> ../../archive/qcmoke.top/cert1.pem
├── chain.pem -> ../../archive/qcmoke.top/chain1.pem
├── fullchain.pem -> ../../archive/qcmoke.top/fullchain1.pem
├── privkey.pem -> ../../archive/qcmoke.top/privkey1.pem
└── README
可以通过如下命令查看证书有效期

1
openssl x509 -noout -dates -in /etc/letsencrypt/live/qcmoke.top/cert.pem
¶4. 配置nginx使用证书开通https
¶4.1 配置PFS秘钥(可选)
生成Perfect Forward Security(PFS)键值,这步其实不做也可以。

1
2
3
mkdir /etc/ssl/private/ -p
cd /etc/ssl/private/
openssl dhparam 2048 -out dhparam.pem
Perfect Forward Security(PFS)是个什么东西,中文翻译成完美前向保密,一两句话也说不清楚,反正是这几年才提倡的加强安全性的技术。如果本地还没有生成这个键值,需要先执行生成的命令。
生成的过程还挺花时间的,喝杯咖啡歇会儿吧。
¶4.2 配置nginx站点
1
vim /etc/nginx/conf.d/qcmoke.top.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
server {
server_name qcmoke.top;
listen 80;
#charset utf-8;
#root /usr/share/nginx/html;
#index index.html;
rewrite ^ https://$server_name$request_uri? permanent;
}

server {
listen 443 ssl;
server_name qcmoke.top;
charset utf-8;
root /usr/share/nginx/html;
index index.html index.htm;

#access_log /var/log/nginx/demo.mydomain.com_access.log;
#error_log /var/log/nginx/demo.mydomain.com_error.log;

# letsencrypt生成的文件
ssl_certificate /etc/letsencrypt/live/qcmoke.top/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/qcmoke.top/privkey.pem;

ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets on;

# Perfect Forward Security路径,如果上面没有生成PFS,这一行 可以不用
ssl_dhparam /etc/ssl/private/dhparam.pem;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
# 一般推荐使用的ssl_ciphers值: https://wiki.mozilla.org/Security/Server_Side_TLS
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128:AES256:AES:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK';
ssl_prefer_server_ciphers on;

}
¶4.3 修改防火墙配置
1
2
3
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --permanent --add-port=443/tcp
firewall-cmd --reload
到这里就配置完毕了,浏览器访问http://qcmoke.top会自动跳转到https://qcmoke.top
————————————————
版权声明:本文为CSDN博主「千与千寻之前」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cpongo3/article/details/96152770

posted on 2020-03-18 11:32  枫飞飞  阅读(199)  评论(0编辑  收藏  举报