您当前的位置:首页 > 电脑百科 > 站长技术 > 服务器

使用 nginx 实现在同一个微信公众号授权域名下访问正式版和测试版

时间:2022-07-05 10:55:05  来源:  作者:buyi3013

微信公众号开发过程中必须要在公众号后台设置网页授权域名、JS接口域名和业务域名。比如:h5.juejin.cn。


微信的匹配规则是完全匹配,比如: test.h5.juejin.cn 是不会通过的。


下面使用 Nginx 反向代理实现同一个域名既可以访问正式版,也可以访问测试版。

nginx 配置

server {
    listen       80;
    server_name  h5.juejin.cn;
    
    ### 判断是否跳转到确认页面    开始 start      ========
    set $condiction 'noReferer';
    if ($http_referer){
        set $condiction '';
    }
    ## 打开微信聊天记录中的链接时,微信会先显示一个外链提示页面,点击 继续访问 才能打开网页。此时 Referer = https://weixin110.qq.com/。
    if ($http_referer = "https://weixin110.qq.com/") {
        set $condiction 'noReferer';
    }
    ## 忽略掉访问 /dev-tool 开头的请求
    if ($uri ~* "dev-tool(.*)") {
        set $condiction "$condiction ignoreUri";
    }
    if ($http_cookie ~* "env=(.+?)(?=;|$)") {
        #### cookie 中包含“测试环境”标识
        set $condiction '$condiction isTest';
    }
    if ($http_cookie ~* "ignoreConfirm=(.+?)(?=;|$)") {
        ####  cookie 中包含“首次访问测试环境忽略提示页面”标识
        set $condiction '$condiction ignoreConfirm';
    }
    if ($condiction = 'noReferer isTest') {
        #### 满足条件1(打开网页)、 条件2(测试环境)时跳转到提示页面
        rewrite ^/(.*) /dev-tool?redirect=$request_uri redirect;
    }
    #### 判断是否跳转到确认页面    结束 end      ========

    location / {
        #### 清除 cookie 中的“首次访问测试环境忽略提示页面”标识
        add_header Set-Cookie 'ignoreConfirm=true;expires=Thu, 09 Dec 1970 06:05:42 GMT;path=/';
        #### 判断是否使用测试版   开始 start      ========
        if ($http_cookie ~* "env=(.+?)(?=;|$)") {
            # proxy_pass http://localhost:7001;
            proxy_pass http://localhost:11000;
        }
        #### 判断是否使用测试版    结束 end      ========

        root h5;
        try_files $uri $uri/ /index.html;

        add_header Cache-Control no-store;
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Headers X-Requested-With;
        add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

        # proxy_set_header Host $host:7001;
        ####        微信H5支付 获取用户端ip用   结束 start      ========
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Real-Port $remote_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        ####        微信H5支付 获取用户端ip用   结束 end      ========
    }

    location /dev-tool {
        root dev-tool;
        index index.html index.htm;
    }

    location = /test {
        ### 访问测试环境,使用cookie标识访问的是测试环境;cookie过期时间设置为1000年;
        add_header Set-Cookie 'env=test333;expires=Thu, 09 Dec 3021 06:05:42 GMT;path=/';
        ### 首次开启测试环境时增加“忽略提示页面”标识
        add_header Set-Cookie 'ignoreConfirm=true;expires=Thu, 09 Dec 3021 06:05:42 GMT;path=/';
        rewrite ^/(.*) / redirect;
    }
}

nginx 文件目录:

使用 nginx 实现在同一个微信公众号授权域名下访问正式版和测试版

 

dev-tool 文件夹目录结构:

注意在根目录 dev-tool 中还有文件夹 dev-tool

使用 nginx 实现在同一个微信公众号授权域名下访问正式版和测试版

 

index.html 文件内容见附录:index.html

本地测试

所需软件: Releases · oldj/SwitchHosts · GitHub

1. 将 h5.juejin.cn 解析到本地ip

# 172.16.3.1 换成自己机器的ip,使用 127.0.0.1 也可以,如果要支持手机访问,必须指定 ip
172.16.3.16 h5.juejin.cn
使用 nginx 实现在同一个微信公众号授权域名下访问正式版和测试版

 

2. 配置 nginx

将 配置 粘贴到 nginx.conf 文件中

3. 将网页放入对应目录中

4。浏览器访问

正式版:http://h5.juejin.cn

测试版:http://h5.juejin.cn/test

附赠小知识

nginx 中的 或 (||)、且(&&)运算

nginx 中没有或、且运算符,使用以下方式代替:

location /{
    set $condiction '';
    if ($http_referer  = ''){
        #### 打开网页或刷新网页时 Referer 表头为空
        set $condiction 'noReferer';
    }
    if ($http_cookie ~* "env=(.+?)(?=;|$)"){
        set $condiction '$condiction isTest';
    }
    if ($condiction = 'noReferer isTest'){
        #### 满足条件1(打开网页或刷新网页)、 条件2(测试环境)时跳转到提示页面
        rewrite ^/(.*) /dev-tool?redirect=$request_uri redirect;
    }
}

判断请求 cookie 中是否包含测试环境标识:

location = /test{
    if ($http_cookie ~* "env=(.+?)(?=;|$)"){
        add_header Set-Cookie 'env=test1;expire=Tue, 09 Nov 2021 02:39:01 GMT;path=/';
    }
}

附录

dev-tool/dev-tool/index.html 文件内容:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提示</title>
    </title>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.0.1/weui.min.css">
    <script type="text/JAVAscript" src="https://res.wx.qq.com/t/wx_fed/cdn_libs/res/weui/1.2.3/weui.min.js"></script>
</head>

<body>
    <script>
        /*
   设置cookie
   name:键
   value:值
   expire:过期时间
   */
        function setCookie(name, value, expire) {
            var exp = new Date();
            exp.setTime(exp.getTime() + expire * 24 * 60 * 60 * 1000 * 1);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
        };
        //根据键获取cookie
        function getCookie(name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        };
        //删除cookie
        function delCookie(name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = getCookie(name);
            if (cval != null)
                document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";Path=/";
        };


        function getQueryVariable(variable) {
            var url = window.location.href;
            var str = url.split('?');
            var query = str[1];
            var vars = query.split('&');
            console.log(query, str, vars);
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                console.log(pair);
                if (pair[0] == variable) {
                    return pair[1];
                }
            }
            return (false);
        }
        // console.log(getQueryVariable('redirect'));
        // console.log(getQueryVariable("redirect"));

        // var redirectUrl = getQueryVariable('redirect');

        var redirectUrl = window.location.href.split("redirect=")[1]
        console.log(redirectUrl);



        function toTest() {
            console.log('yes');
            window.location.replace(redirectUrl);
        }
        function toRelese() {
            console.log('no');
            delCookie("env");
            window.location.replace(redirectUrl);
        }
        weui.confirm('你正在访问测试版,是否继续?', {
            title: '提示',
            buttons: [{
                label: '访问正式版',
                type: 'default',
                onClick: function () { console.log('no'); toRelese(); }
            }, {
                label: '确定',
                type: 'primary',
                onClick: function () { console.log('yes'); toTest(); }
            }]
        });
    </script>

</body>

</html>

问题一:uni-App 打包出来的 H5 版本,使用这个 nginx 配置会报 404

location / {
    set $condiction '';
    if ($http_referer  = ''){
        #### 打开网页或刷新网页时 Referer 表头为空
        set $condiction 'noReferer';
    }
}

可以改为这样:

location / {
    set $condiction 'noReferer';
    if ($http_referer){
        set $condiction '';
    }
}

问题二:访问页面路径返回404, uni-app 打包出来的 H5 版本,直接访问访问某个页面的链接时,使用这个 nginx 配置会报 404

问题描述:

部署 uni-app 打包出来的 H5 版本(目前只测试了这个,其他未测试)
访问首页没问题, 如: http://h5.juejin.cn
访问页面路径报错 404,如:
http://h5.juejin.cn/pages/mine/index

错误原因:

if 指令在 location 上下文中使用会有些问题。官网文档:If is Evil… when used in location context | NGINX

解决方法:

把部分 if 指令放到 server 上下文中

解决此问题感谢:

  1. try-files-always-returns-404-with-variable @ https://stackoverflow.com/questions/44077452/try-files-always-returns-404-with-variable
  2. https://segmentfault.com/q/1010000039845108

修改前(前往修改后):

server {
    listen       80;
    server_name  h5.juejin.cn;


    location / {
        #### 判断是否跳转到确认页面    开始 start      ========
        # ============================================ uni-app 打包出来的 H5 版本,使用这个会报 404
        # set $condiction '';
        # if ($http_referer  = ''){
        #     set $condiction 'noReferer';
        # }
        # =====================================================
        set $condiction 'noReferer';
        if ($http_referer){
            #### 打开网页或刷新网页时 Referer 表头为空
            set $condiction '';
        }
        if ($http_cookie ~* "env=(.+?)(?=;|$)"){
            #### cookie 中包含“测试环境”标识
            set $condiction '$condiction isTest';
        }
        if ($http_cookie ~* "ignoreConfirm=(.+?)(?=;|$)"){
            ####  cookie 中包含“首次访问测试环境忽略提示页面”标识
            set $condiction '$condiction ignoreConfirm';
        }
        #### 清除 cookie 中的“首次访问测试环境忽略提示页面”标识
        add_header Set-Cookie 'ignoreConfirm=true;expires=Thu, 09 Dec 1970 06:05:42 GMT;path=/';
        if ($condiction = 'noReferer isTest'){
            #### 满足条件1(打开网页)、 条件2(测试环境)时跳转到提示页面
            rewrite ^/(.*) /dev-tool?redirect=$request_uri redirect;
        }
        #### 判断是否跳转到确认页面    结束 end      ========

        #### 判断是否使用测试版   开始 start      ========
        if ($http_cookie ~* "env=(.+?)(?=;|$)"){
            # proxy_pass http://localhost:7001;
            proxy_pass http://localhost:11000;
        }
        #### 判断是否使用测试版    结束 end      ========

        root    h5;
        index   index.html index.htm;
        # try_files $uri $uri/ /index.html;

        add_header Cache-Control no-store;
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Headers X-Requested-With;
        add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

        # proxy_set_header Host $host:7001;
        ####        微信H5支付 获取用户端ip用   结束 start      ========
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Real-Port $remote_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        ####        微信H5支付 获取用户端ip用   结束 end      ========


    }
    location /dev-tool{
        root    dev-tool;
        index   index.html index.htm;
    }

    location = /test{
        ### 访问测试环境,使用cookie标识访问的是测试环境;cookie过期时间设置为1000年;
        add_header Set-Cookie 'env=test;expires=Thu, 09 Dec 3021 06:05:42 GMT;path=/';
        ### 首次开启测试环境时增加“忽略提示页面”标识
        add_header Set-Cookie 'ignoreConfirm=true;expires=Thu, 09 Dec 3021 06:05:42 GMT;path=/';
        rewrite ^/(.*) / redirect;
    }
}

修改后:

server {
    listen       80;
    server_name  h5.juejin.cn;
    
    ### 判断是否跳转到确认页面    开始 start      ========
    set $condiction 'noReferer';
    if ($http_referer){
        set $condiction '';
    }
    ## 打开微信聊天记录中的链接时,微信会先显示一个外链提示页面,点击 继续访问 才能打开网页。此时 Referer = https://weixin110.qq.com/。
    if ($http_referer = "https://weixin110.qq.com/") {
        set $condiction 'noReferer';
    }
    ## 忽略掉访问 /dev-tool 开头的请求
    if ($uri ~* "dev-tool(.*)") {
        set $condiction "$condiction ignoreUri";
    }
    if ($http_cookie ~* "env=(.+?)(?=;|$)") {
        #### cookie 中包含“测试环境”标识
        set $condiction '$condiction isTest';
    }
    if ($http_cookie ~* "ignoreConfirm=(.+?)(?=;|$)") {
        ####  cookie 中包含“首次访问测试环境忽略提示页面”标识
        set $condiction '$condiction ignoreConfirm';
    }
    if ($condiction = 'noReferer isTest') {
        #### 满足条件1(打开网页)、 条件2(测试环境)时跳转到提示页面
        rewrite ^/(.*) /dev-tool?redirect=$request_uri redirect;
    }
    #### 判断是否跳转到确认页面    结束 end      ========

    location / {
        #### 清除 cookie 中的“首次访问测试环境忽略提示页面”标识
        add_header Set-Cookie 'ignoreConfirm=true;expires=Thu, 09 Dec 1970 06:05:42 GMT;path=/';
        #### 判断是否使用测试版   开始 start      ========
        if ($http_cookie ~* "env=(.+?)(?=;|$)") {
            # proxy_pass http://localhost:7001;
            proxy_pass http://localhost:11000;
        }
        #### 判断是否使用测试版    结束 end      ========

        root h5;
        try_files $uri $uri/ /index.html;

        add_header Cache-Control no-store;
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Headers X-Requested-With;
        add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

        # proxy_set_header Host $host:7001;
        ####        微信H5支付 获取用户端ip用   结束 start      ========
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Real-Port $remote_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        ####        微信H5支付 获取用户端ip用   结束 end      ========
    }

    location /dev-tool {
        root dev-tool;
        index index.html index.htm;
    }

    location = /test {
        ### 访问测试环境,使用cookie标识访问的是测试环境;cookie过期时间设置为1000年;
        add_header Set-Cookie 'env=test333;expires=Thu, 09 Dec 3021 06:05:42 GMT;path=/';
        ### 首次开启测试环境时增加“忽略提示页面”标识
        add_header Set-Cookie 'ignoreConfirm=true;expires=Thu, 09 Dec 3021 06:05:42 GMT;path=/';
        rewrite ^/(.*) / redirect;
    }
}


Tags:nginx   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
nginx 80端口重定向到443端口,也就是http访问自动跳转到https 配置如下:一、按照如下格式修改nginx.conf 配置文件,80端口会自动转给443端口,这样就强制使用SSL证书加密了。访问...【详细内容】
2022-10-09  Tags: nginx  点击:(31)  评论:(0)  加入收藏
 Nginx 服务器的反向代理服务是其最常用的重要功能,由反向代理服务也可以衍生出很多与此相关的 Nginx 服务器重要功能,比如后面会介绍的负载均衡。本篇博客我们会先介绍 Ngin...【详细内容】
2022-09-28  Tags: nginx  点击:(33)  评论:(0)  加入收藏
本来想安装宝塔一键搭建lnmp环境的,但是wsl 2安装宝塔之后用不了,而且连wsl 2的网络都没了,所以无奈之下只好手动一个个装,安装nginx之后,在conf.d目录下创建文件lw_test.conf,内...【详细内容】
2022-09-18  Tags: nginx  点击:(55)  评论:(0)  加入收藏
文章目录 nginx做负载均衡服务器,配置动静分离3. 在134主机主机部署lnmp,在动态资源4.1 在128主机安装httpd,做静态资源4.2 在129主机源码安装nginx并配置负载均衡器,进行调度5....【详细内容】
2022-09-07  Tags: nginx  点击:(87)  评论:(0)  加入收藏
Nginx简介Nginx (发音为“Engine-x”)是一种开源软件,最初被设计为高性能Web服务器。今天,Nginx可以完成其他一些任务,包括缓存服务器,反向代理服务器,负载平衡器等等。WEB服务器目...【详细内容】
2022-09-05  Tags: nginx  点击:(89)  评论:(0)  加入收藏
问题一般在正式的环境下,通过给域名添加子路径(如oss)用于下载文件服务器上的文件。但这种设置子路径的方式不能直接通过API上传文件,创建桶等,鉴于安全,也不能让这种子路径拥有创...【详细内容】
2022-09-05  Tags: nginx  点击:(137)  评论:(0)  加入收藏
软硬件环境 ubuntu 16.04 Android Studio 2.1.3 OTT BOx with android 5.1.1 nginx 1.11.3 nginx-rtmp-module vitamio前言当下,直播已经成为网络热词,它不单单是指传统广播...【详细内容】
2022-09-03  Tags: nginx  点击:(61)  评论:(0)  加入收藏
Caddy是一个强大且可扩展的Web服务器、代理服务器。Caddy使用Go语言开发,支持HTTP/2IPv6、Markdown、WebSockets、FastCGI、模板等等,目前已经超过42k star。功能特性 相比N...【详细内容】
2022-09-01  Tags: nginx  点击:(61)  评论:(0)  加入收藏
一、docker直接运行一个nginx应用# docker run -d -p 8080:80 nginxUnable to find image &#39;nginx:latest&#39; locallylatest: Pulling from library/nginxa330b6cecb98...【详细内容】
2022-07-27  Tags: nginx  点击:(72)  评论:(0)  加入收藏
linux系统中Nginx+FFmPeg实现网页监控视频播放配置过程1.安装好的nginx上添加模块nginx-http-fiv-module-master此模块是rtmp模块的升级版,有它所有的功能,因此安装它(1)从Git...【详细内容】
2022-07-24  Tags: nginx  点击:(70)  评论:(0)  加入收藏
▌简易百科推荐
FTP服务软件安装包: vsftpd默认发布目录: /var/ftp协议接口: 21/tcp服务配置文件: /etc/vsftpd/vsftpd.conf报错id的解析:500 ##文件系统权限过大530 ##用户认证失败550 ##服务本...【详细内容】
2022-10-17  沪飘运维    Tags:FTP   点击:(9)  评论:(0)  加入收藏
一个朋友说他遇到这样一个问题,同样的服务器别人可以连接,自己却无法连接,捣鼓了好久都无法解决,很是郁闷。这个问题,刚好我之前也遇到过,后来完美解决了,这就给大家分享一下我的解...【详细内容】
2022-10-14  萌小翊  搜狐号  Tags:服务器   点击:(14)  评论:(0)  加入收藏
nginx 80端口重定向到443端口,也就是http访问自动跳转到https 配置如下:一、按照如下格式修改nginx.conf 配置文件,80端口会自动转给443端口,这样就强制使用SSL证书加密了。访问...【详细内容】
2022-10-09  运维技术站  今日头条  Tags:重定向   点击:(31)  评论:(0)  加入收藏
本文主要分享了如何搭建一个类似阿里云OSS的对象存储服务器。以windows环境下MinIO的搭建举例说明,linux环境下的搭建网上也有很多教程,请自行搜索相关资料。一、下载地址:http...【详细内容】
2022-10-07  吾日三省Java  今日头条  Tags:OSS服务器   点击:(32)  评论:(0)  加入收藏
一、软硬件准备:软件VMware软件,这里我以VMware&reg; Workstation 15 Pro为例;Centos镜像,这里我以centos8.3为例;硬件 二、在window系统部署linux系统,这里以centos为例1、下载...【详细内容】
2022-10-06  微笑橙子mR  今日头条  Tags:DHCP   点击:(27)  评论:(0)  加入收藏
对于新手建议可以弄一台免费的虚拟主机来学习网站搭建,在使用免费主机的这段时间你会掌握基本的建站技能,以及确定自己是否喜欢,下面推荐亲身用过的体验还不错的虚拟主机,均无广...【详细内容】
2022-10-01  智者饭团D  今日头条  Tags:虚拟主机   点击:(40)  评论:(0)  加入收藏
 Nginx 服务器的反向代理服务是其最常用的重要功能,由反向代理服务也可以衍生出很多与此相关的 Nginx 服务器重要功能,比如后面会介绍的负载均衡。本篇博客我们会先介绍 Ngin...【详细内容】
2022-09-28  微笑橙子mR  今日头条  Tags:nginx   点击:(33)  评论:(0)  加入收藏
使用在 Kubernetes 上运行的 Kafka 在 API 端点之间流式传输消息。 Apache Kafka 不仅仅是一个消息传递代理。它有一个由不同组件组成的丰富生态系统。有用于导入和导出数据...【详细内容】
2022-09-28  qaseven     Tags:Apache Kafka   点击:(22)  评论:(0)  加入收藏
作者:rangobai,腾讯CSIG数据工程师| 导语要有性能意识,量变引起质变,简单如一行日志都会在高并发的情况引发血案,考验着研发的技术功底一 案件背景9月的某个上午,业务侧突然反...【详细内容】
2022-09-28  腾讯技术工程    Tags:内存泄漏   点击:(23)  评论:(0)  加入收藏
如何搭建IIS+MySQL+PHP环境教程方法首先下载php-5.2.0-win32.zip,mysql-noinstall-5.0.22-win32.zip和phpMyAdmin-2.9.1.1-all-languages.zip。这三个文件的下载地址可以在百...【详细内容】
2022-09-27  艾西0FF0  今日头条  Tags:PHP环境   点击:(39)  评论:(0)  加入收藏
站内最新
站内热门
站内头条