Linux - Nginx

nginx做为静态服务器和反向代理服务器

安装nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 查看nginx版本,内核需要2.6以上
uname -a

#安装gcc
yum install gcc gcc-c++ pcre-devel zlib zlib-devel openssl openssl-devel

gcc 编译c
gcc-c++ 编译c++
pcre-devel 解析perl正则
zlib 用于压缩
zlib-devel 用于开发
openssl 用于ssl加密

#安装nginx
./configure
make
make install

#configure配置选项
--prefix=PATH 安装部署后的根目录
--sbin-path 可执行文件的放置路径 基于前面的prefix <prefix>/sbin/nginx
--conf-path 放置配置文件 <prefix>/conf/nginx.conf
--error-log-path <prefix>/logs/errors.log

启动nginx

1
2
./usr/local/sbin/nginx -s stop / reload
-c xxx.conf

将nginx做为静态服务器

case:

1
2
3
4
5
6
server {
location ^~ /static{
alias usr/local/nginx/conf
}

}

明确root和alias的不同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# root
location conf {
root usr/local/nginx;
}

# alias
location conf {
alias usr/local/nginx/conf;
}

alias 要指定到具体的一层文件夹
root 会根据url来映射文件夹

比如:
http://www.xxx.com/conf/test.html
alias的处理 匹配location为conf的规则,将配置的文件夹直接返回给用户
root的处理:匹配到location为conf的规则,提取/conf/test.html 拼接到已配置的文件夹下面

将nginx做为反向代理服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
# 在nginx.conf里面的http模块里面加入
include '/usr/local/nginx/conf/nginx2.conf'
vim nginx2.conf

upstream xxx{
server 112.11.11.11:8080;
}
server{
server_name www.xxx.com;
location / {
proxy_pass http://xxx;
}
}

如何做好负载均衡?

1
2
3
4
5
upstream xxx{
server 111.111.111.111 weight=5(权重,优先转发);
server 222.222.222.222 max_fails=3 fail_timeout=30s(失败3次,30s);
server 333.333.333.333 down(下线);
}

nginx