“这是我参与更文挑战的第19天,活动详情查看: 更文挑战”
上一篇介绍了Nginx基础应用实战第一篇,接下来介绍Nginx基础应用实战第二篇。
虚拟主机
虚拟主机是一种特殊的软硬件技术,它可以将网络上的每一台计算机分成多个虚拟主机,每个虚拟主机可以独立对外提供www服务,这样就可以实现一台主机对外提供多个web服务,每个虚拟主机之间是独立的,互不影响的。
通过nginx可以实现虚拟主机的配置,nginx支持三种类型的虚拟主机配置。
http{
server{
#表示一个虚拟主机
}
}
基于ip的虚拟主机
一块主机绑定多个ip地址,即一块网卡下可以绑定多个ip。
基于域名的虚拟主机
配置本地hosts
192.168.85.200 moe.com
192.168.85.200 zoe.com
配置nginx
配置2个目录
[root@localhost /]# ll -R mzoe/
mzoe/:
total 0
drwxr-xr-x. 2 root root 24 Jun 4 01:16 moe.com
drwxr-xr-x. 2 root root 24 Jun 4 01:16 zoe.com
mzoe/moe.com:
total 4
-rw-r--r--. 1 root root 20 Jun 4 01:16 index.html
mzoe/zoe.com:
total 4
-rw-r--r--. 1 root root 23 Jun 4 01:16 index.html
配置2个server
server {
listen 80;
server_name moe.com;
location / {
root /mzoe/moe.com/;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name zoe.com;
location / {
root /mzoe/zoe.com/;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
基于端口的虚拟主机
同一ip不同端口
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 88;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
重新加载配置与排查错误
重新加载配置
systemctl reload nginx.service
查看错误详情
systemctl status nginx.service -l
反向代理
proxy_pass
注意proxy_pass 最后的斜杠,不写访问不了!!!
server {
listen 80;
server_name mrc.com;
location /mrc {
proxy_pass http://www.baidu.com/;
}
}
基于反向代理的负载均衡
upstream mrc {
server 192.168.85.200:88;
server 192.168.85.200:99;
}
server {
listen 80;
server_name mrc.com;
location / {
proxy_pass http://mrc/;
}
}
server {
listen 88;
server_name moe.com;
location / {
root /mzoe/moe.com/;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 99;
server_name zoe.com;
location / {
root /mzoe/zoe.com/;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
weight(权重)
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
upstream mrc {
server 192.168.85.200:88 weight=10 down;
server 192.168.85.200:99 weight=1;
server 192.168.85.200:100 weight=10 backup;
}
- down:表示当前的server暂时不参与负载
- weight:默认为1,weight越大,负载的权重就越大。
- backup:其它所有的非backup机器down或者忙的时候,请求backup机器。
域名、DNS、SSL
域名申请
域名申请有多重渠道,这里介绍阿里云上申请域名。
域名控制台
接下来进入域名控制台,申请进一步的认证信息,必须认证完后,域名才能通过。
域名解析
域名申请完成后,接下来配置域名解析,添加域名与IP映射规则。
SSL证书申请
这里我申请的是腾讯云 TrustAsia SSL证书 - 域名型免费版(DV),当然阿里云里也有相关SSL证书的申请。大家可以自行申请即可。
SSL证书与域名绑定
总结
本篇介绍了Nginx可以用来反向代理、负载均衡、虚拟主机的配置,接着介绍了域名申请、DNS配置、公网配置HTTPS需要的SSL证书配置。下一篇介绍Nginx服务器上安装证书SSL。
欢迎大家关注公众号(MarkZoe)互相学习、互相交流。