Practical Implementation of Reverse Proxy and Cross-Domain on Github Pages


Deploying a web app on Github Pages (hereinafter referred to as gp) is very convenient and elegant, but there is one issue, that is, the cross-domain problem when accessing the interface.

Solution Approach

Typically, we directly resolve the domain name to the nginx server, and then use nginx reverse proxy to proxy the front-end api path to the api server. On the other hand, if the project is deployed on Github Pages (gp), we need to resolve the domain name directly to the gp server. In this way, a conflict arises, requiring some additional configurations. So, we might as well resolve the domain name directly to nginx, and then use nginx to proxy the front-end to gp, and the api to the backend. However, this does not follow the configuration rules of gp, and we cannot enable the enforce https feature of gp. But this redirection step can be directly implemented on the nginx server.



First, you need to prepare a server, then install and enable nginx, and resolve the domain name that you need to configure for the front end to this server. In addition, you also need to configure the backend server and complete the domain name resolution, such as

Deploy gh

Refer to my previous article to properly deploy gh, and fill in in the custom domain column. Since the address was not resolved to gh when parsing, the Enforce Https option cannot be checked, and it is currently inaccessible.

Configure nginx reverse proxy

    listen 80;
    server_name; # 填上自己的域名
    location /api { # 配置前端 api 的路径
        proxy_pass; # 填上要转发的 api 服务器地址
        # 这里有一个需要注意的地方如果填的是 (末尾无斜杠)
        # 那么, 当前端访问 时
        # nginx 会将请求转发到
        # 而如果填的是
        # 那么, 当前端访问 时
        # nginx 会将请求转发到  
    location / {
        proxy_redirect off;
        proxy_set_header host $host;
        proxy_set_header x-real-ip $remote_addr;
        proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
        # 填上你的 gp 的二级域名, 比如我的是
    access_log /var/log/nginx/sorcererxw.com_access.log;

Alright, then reload nginx.

nginx -s reload

At this point, if you visit, it should be accessible, and you should also be able to directly access the API interface from the front end. The principle is that, although the front-end traffic is directly forwarded to, through the domain name in the current address bar, gh will display the corresponding front-end page.

Configure Https redirection

The most convenient method is to directly use letsencrypt's certbot for configuration, and install it according to

certbot --nginx

Remember to select redirect https.