Appearance
虚拟主机
原本一台服务器只能对应一个站点,通过虚拟主机技术可以虚拟化成多个站点同时对外提供服务, 充分利用服务器的资源。
hosts 文件解析域名
打开 C:\Windows\System32\drivers\etc\hosts 添加 192.168.44.101 foo.com
浏览器中访问 http://foo.com,会显示 /html/index.html。
泛域名解析
阿里云的主机记录修改为 *.foo.com,实现多用户二级域名。
通过不同端口号配置虚拟主机
nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# 80 端口
server {
listen 80;
server_name localhost;
location / {
root /www/www;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# 88 端口
server {
listen 88;
server_name localhost;
location / {
root /www/video;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}通过不同域名配置虚拟主机
nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# 二级域名为 www
server {
listen 80;
server_name www.foo.com;
location / {
root /www/www;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# 二级域名为 video
server {
listen 80;
server_name video.foo.com;
location / {
root /www/video;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}server_name 的多种匹配方式
匹配到一个后就不会接着往下匹配了。
nginx
server {
listen 80;
# 完整匹配
server_name video.foo.com;
# 完整匹配,多个域名指向同一主机。
# server_name video.foo.com video2.foo.com;
# 通配符匹配
# server_name *.foo.com;
# 通配符结束匹配
# server_name www.foo.*;
# 正则匹配,~ 表示正则的开始符,$ 表示正则的结束符。
# server_name ~^[0-9]+\.foo\.com$;
location / {
root /www/video;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}多用户二级域名
配置泛解析后,nginx 反向代理将所有请求转发到业务服务器,业务服务器内部会判断是不是二级 域名,如果是的话会取出二级域名的部分,从数据库中查找出对应的数据,返回给 nginx,nginx 再返回给浏览器。
短网址
短网址运维系统中有一个数据库,存储着用户提交的真实网址和通过 uuid 生成的短网址,nginx 反向代理到运维服务器,运维服务器取出短网址去数据库中匹配,然后重定向到真实网址。
httpdns
httpdns 是基于 http 协议的动态 dns 服务器,由 nginx 实现。
适用于手机 App 或 C/S 架构使用,可以在软件内预埋几个 ip 地址,这些 ip 地址就是 nginx 服务器的地址,当访问域名时通过参数的形式将域名传递给 nginx,如 192.168.44.101/get?url=foo.com,对应的解析结果存储在数据库或内存中,nginx 服务器拿到 解析结果后返回给客户端。
不适用于 web 端,因为浏览器第一次请求就需要知道填入的域名的地址,首先浏览器不允许外部完 成域名解析然后返回结果,其次浏览器解析完后就访问了,等不到你将解析结果返回。