Nginx的使用

简介

Nginx是一款轻量级服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东新浪网易腾讯淘宝等。

安装Linux端

官方网站:http://nginx.org/en/download.html

把源码包解压在服务器上,然后

1
2
3
# 编译安装
./configure --prefix=路径
make && make install

如果不能安装则需要安装好环境,具体百度。

常用指令

1
2
3
4
5
6
7
8
9
10
11
12
nginx -v #查看版本
nginx -V #详细信息

# 进入nginx程序文件夹
cd /usr/sbin
./nginx #启动
./nginx -s stop #查出nginx进程id再使用kill命令强制杀掉进程。
./nginx -s quit #待nginx进程处理任务完毕进行停止。
./nginx -s reload #改了配置文件后需要重启nginx

#查询nginx状态
ps aux | grep nginx

常用功能实现

一个IP的服务器实现多个网页

同域名不同端口

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
# nginx.conf配置文件
server{
listen 80;
server_name blog.drehtsich.cc; # 解析的域名

#charset koi8-r;

#access_log logs/host.access.log main;

location/{
root /var/www/html(1); #网页文件路径
index index.html index.htm;
}
}
server{
listen 8080;
server_name blog.drehtsich.cc; # 解析的域名

#charset koi8-r;

#access_log logs/host.access.log main;

location/{
root /var/www/html(2); #网页文件路径
index index.html index.htm;
}
}

不同域名同一端口

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
# nginx.conf配置文件
# 两个域名都要解析到同一个ip
server{
listen 80;
server_name blog.drehtsich.cc; # 解析的域名

#charset koi8-r;

#access_log logs/host.access.log main;

location/{
root /var/www/html(1); #网页文件路径
index index.html index.htm;
}
}
server{
listen 80;
server_name dl.drehtsich.cc; # 解析的域名

#charset koi8-r;

#access_log logs/host.access.log main;

location/{
root /var/www/html(2); #网页文件路径
index index.html index.htm;
}
}

Nginx常用模块功能

文件共享功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# nginx.conf配置文件
server{
listen 80;
server_name dl.drehtsich.cc; # 解析的域名

autoindex on; #目录开启;
autoindex_exact_size off; #文件大小;
autoindex_localtime on; #文件修改时间(UTC)
charset utf-8; #文字编码

location/{
root /var/www/html(2); #网页文件路径
index index.html index.htm;
}
}
#修改完文件后,需要重载nginx

网页身份验证功能

利用htpasswd创建密码文件,再使用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
# centos
yum install -y httpd-tools
# debian
apt-get install apache2-utils

#使用htpasswd创建密码文件
htpasswd -bc path/htpasswd.users account password # -c会覆写文件,只想新增用户密码只需-b

# nginx.conf配置文件
server{
listen 80;
server_name dl.drehtsich.cc; # 解析的域名

#身份验证;
auth_basic "Identity Authentication"; #提示语,随便填
auth_basic_user_file /path/htpasswd.users; #密码文件路径

location/{
root /var/www/html(2); #网页文件路径
index index.html index.htm;
}
}

#修改完文件后,需要重载nginx

htpasswd命令帮助

1
2
3
4
5
6
7
8
9
10
11
12
13
htpasswd [-cimBdpsDv] [-C cost] passwordfile username
htpasswd -b[cmBdpsDv] [-C cost] passwordfile username password

htpasswd -n[imBdps] [-C cost] username
htpasswd -nb[mBdps] [-C cost] username password
-c 创建一个文件
-b 命令行中直接输入除了账号外的密码
-m 使用MD5加密(默认)
-B 使用bcrypt加密(非常安全)Force bcrypt encryption of the password (very secure).
-d 使用CRYPT加密
-s 使用SHA加密
-p 不对密码加密
-D 删除特定用户