使用 NGINX 转发 Github Pages 站点

背景

新的 Blog 是基于 Hugo 搭建的,原始博客内容和生成的静态资源,都是托管在 Github 仓库里面的。但 Github Pages 有时候会抽风,并且访问速度并不是很稳定,因此萌生了使用 NGINX 反向代理 Github Pages 的想法。

解决

基本原理就是将目标站点(Github Pages) 作为一个 upstream 服务,然后 NGINX 负责将所有流量都转发到 upstream 即可。因此,我们的配置文件编写就比较简单了,只需要注意 Host 等信息需要使用 upstream 站点的信息(Github Pages)。

blog-proxy.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
30
31
32
server{
    listen 80;
    server_name your.blog.com;
    return 301 https://your.blog.com$request_uri;
}

server{
    listen 443 ssl http2;
    server_name your.blog.com;

    ssl_certificate   /opt/cert/sslfile.pem;
    ssl_certificate_key  /opt/cert/sslfile.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_redirect off;
        proxy_set_header Host yourblog.github.io;    # 填写 Github Pages 的地址。
        proxy_set_header X-Host yourblog.github.io;  # 填写 Github Pages 的地址。
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # Cache pages.
        proxy_cache_valid 200 206 304 301 302 1d;    # 配置缓存过期时间。
        proxy_cache_valid any 1d;
        proxy_cache_key $uri;

        proxy_pass https://yourblog.github.io;       # 填写 Github Pages 的地址。
    }
}
Built with Hugo
主题 StackJimmy 设计