接前文《在自己的服务器上搭起Hexo博客》,在服务器上创建hexo博客成功后,可以在外网用服务器外网ip访问博客了。但一般博客对外的方式都是用域名访问的,这篇文章将记录如何将博客配置成外网域名访问(支持配置多个子域名去访问多个博客)。
准备:1.在服务器上搭起几个准备配置域名的博客应用;2.购买一个域名,并实名和备案,这里是使用阿里云购买的域名;
准备完成后,就可以配置域名和博客的映射了。

在域名服务商网站上配置域名解析设置

这里使用的阿里云,就在阿里云个人管理控制台中,打开对应域名(假如为:myhost.com)的解析设置页。点击“添加记录”,在弹窗中,主机记录框中输入三级域名“test1”,记录值框中输入服务器外网ip地址(假如为 10.10.10.10)。
pic
同样的,再配置一个三级域名“test2”到服务器外网ip地址。
pic
这样,在外网用“http://test1.myhost.com” 或 “http://test2.myhost.com” 就可以访问服务器的80端口应用了。

使用nginx配置80端口用不同域名代理到不同的应用上

打开nginx目录下的conf目录,配置nginx.conf文件,在http的配置中第一行增加一行include ./include/*.conf; ,即把include目录下的conf文件导入进来。
在conf目录中新加include目录,新建 myhost.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
upstream p8001 {
ip_hash;
server localhost:8001;
}
server {
listen 80;
server_name test1.myhost.com;
location / {
proxy_pass http://p8001;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

upstream p8002 {
ip_hash;
server localhost:8002;
}
server {
listen 80;
server_name test2.myhost.com;
location / {
proxy_pass http://p8002;
proxy_redirect default;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

这样,“http://test1.myhost.com” 和 “http://test2.myhost.com” 就分别别解析到服务器的8001和8002端口了。
然后,将自己的两个博客应用分别配置到8001和8002端口,创建blog.conf文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 8001;
server_name localhost;
location / {
root /workspace/blog1/public; #这里填博客文件的实际路径
index index.html index.htm;
}
}
server {
listen 8002;
server_name localhost;
location / {
root /workspace/blog2/public;
index index.html index.htm;
}
}

至此,nginx配置完成,重启nginx使配置生效:

1
2
nginx -s stop
nginx

现在,在浏览器访问“http://test1.myhost.com” 和 “http://test2.myhost.com” ,就可以访问到自己的两个博客了。

附录

域名绑定七牛云(融合 CDN 加速域名)

1.在七牛云注册账号,打开“对象存储”(https://portal.qiniu.com/bucket),新建存储空间(例如为"granary"),上传文件;
2.打开“融合CDN”-“域名管理”-“创建域名”,在加速域名处输入域名,例如“granary.myhost.com”,源站配置处选择对象存储中的空间”granary”,点击创建;
3.在域名管理中查看“granary.myhost.com”的配置信息,copy域名的CNAME值;
4.在域名服务商网站打开域名的解析设置页,添加一条CNAME记录,将主机记录”granary”解析到七牛云提供的CNAME值即可;
5.配置完成几分钟后生效,浏览器访问“granary.myhost.com”,即可访问到”granary”存储空间的index.html文件。
6.备注:七牛存储空间上文件会有缓存时间,文件改动时,访问最新文件需要请求加时间戳参数,或在”融合CND”-“刷新预取”中刷新文件链接。