微信小程序通过webview访问外部连接,但是外部的服务器没有存放小程序的校验文件,还有那些方式可以实现

位置:首页 / 技术中心 / 微信小程序原生

微信小程序原生 Admin 2025-12-09 17:02:58 105

使用nginx操作

https://www.doubao.com/thread/we004e95c8ed23a60

nginx完整代码如下

server

{

       listen 80;

    listen 443 ssl;

    listen 443 quic;

    http2 on;

    server_name wst.77gwy.cn;

    index index.html index.htm default.htm default.html;

    root /www/wwwroot/wst.77gwy.cn;


    # 保留你原有 SSL/证书/禁止访问等配置...

    #CERT-APPLY-CHECK--START

    # 用于SSL证书申请时的文件验证相关配置 -- 请勿删除并保持这段设置在优先级高的位置

    include /www/server/panel/vhost/nginx/well-known/wst.77gwy.cn.conf;

    #CERT-APPLY-CHECK--END


    #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则

    #error_page 404/404.html;

    ssl_certificate    /www/server/panel/vhost/cert/wst.77gwy.cn/fullchain.pem;

    ssl_certificate_key    /www/server/panel/vhost/cert/wst.77gwy.cn/privkey.pem;

    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;

    ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;

    ssl_prefer_server_ciphers on;

    ssl_session_cache shared:SSL:10m;

    ssl_session_timeout 10m;

    add_header Strict-Transport-Security "max-age=31536000";

    add_header Alt-Svc 'quic=":443"; h3=":443"; h3-29=":443"; h3-27=":443";h3-25=":443"; h3-T050=":443"; h3-Q050=":443";h3-Q049=":443";h3-Q048=":443"; h3-Q046=":443"; h3-Q043=":443"';

    error_page 497  https://$host$request_uri;


    #SSL-END


    # #ERROR-PAGE-START  错误页配置,可以注释、删除或修改

    # #error_page 404 /404.html;

    # #error_page 502 /502.html;

    # #ERROR-PAGE-END


    # #REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效

    # include /www/server/panel/vhost/rewrite/html_wst.77gwy.cn.conf;

    # #REWRITE-END


    # #禁止访问的文件或目录

    # location ~ ^/(\.user.ini|\.htaccess|\.git|\.env|\.svn|\.project|LICENSE|README.md)

    # {

    #     return 404;

    # }


    # #一键申请SSL证书验证目录相关设置

    # location ~ \.well-known{

    #     allow all;

    # }


    # #禁止在证书验证目录放入敏感文件

    # if ( $uri ~ "^/\.well-known/.*\.(php|jsp|py|js|css|lua|ts|go|zip|tar\.gz|rar|7z|sql|bak)$" ) {

    #     return 403;

    # }


    # location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf)$

    # {

    #     expires      30d;

    #     error_log /dev/null;

    #     access_log /dev/null;

    # }


    # location ~ .*\\.(js|css)?$

    # {

    #     expires      12h;

    #     error_log /dev/null;

    #     access_log /dev/null;

    # }


    # ========== 核心修改1:全量转发所有静态资源请求 ==========

    # 匹配政府页面内的所有静态资源路径(根据实际路径调整)

    location ~ ^/(bog-bsdt|static|assets|js|css|images)/ {

        # 直接转发到政府服务器(无需 /forward/ 前缀)

        proxy_pass https://hf.ahzwfw.gov.cn$request_uri;

        

        # 透传请求头(和 /forward/ 一致)

        proxy_set_header Host hf.ahzwfw.gov.cn;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_set_header Referer https://hf.ahzwfw.gov.cn/;

        proxy_set_header User-Agent $http_user_agent;

        

        # 超时/跨域配置

        proxy_connect_timeout 30s;

        proxy_read_timeout 30s;

        proxy_send_timeout 30s;

        proxy_hide_header X-Frame-Options;

        add_header Access-Control-Allow-Origin *;

    }


    # ========== 核心修改2:修正 /forward/ 主页面转发 ==========

    location /forward/ {

        # 去掉 rewrite(避免路径截断)

        # rewrite ^/forward/(.*)$ /$1 break; 


        # proxy_pass 末尾加 /,确保路径完整拼接

        proxy_pass https://hf.ahzwfw.gov.cn/;


        # 透传请求头(强制模拟政府域名的合法请求)

        proxy_set_header Host hf.ahzwfw.gov.cn;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Forwarded-Proto $scheme;

        # 关键:强制设置 Referer 为政府域名(政务网必验)

        proxy_set_header Referer https://hf.ahzwfw.gov.cn/;

        proxy_set_header User-Agent $http_user_agent;

        proxy_set_header Origin https://hf.ahzwfw.gov.cn;


        # ========== 核心:自动替换页面内所有相对路径 ==========

        # 把页面里的 "/xxx" 替换为 "/forward/xxx"(让资源请求走代理)

        sub_filter 'src="/' 'src="/forward/';

        sub_filter 'href="/' 'href="/forward/';

        sub_filter 'action="/' 'action="/forward/';

        sub_filter 'url("/' 'url("/forward/';

        # 把页面里的 "./xxx" 替换为 "/forward/当前目录/xxx"(适配相对路径)

        sub_filter 'src="./' 'src="/forward/bog-bsdt/static/workProcess/components/';

        sub_filter 'href="./' 'href="/forward/bog-bsdt/static/workProcess/components/';

        # 替换所有匹配项(不止第一个)

        sub_filter_once off;

        # 匹配所有文本类型文件

        sub_filter_types text/html text/css text/javascript application/json;


        # 其他基础配置

        proxy_buffering on;

        proxy_buffer_size 16k;

        proxy_buffers 4 64k;

        proxy_connect_timeout 30s;

        proxy_read_timeout 30s;

        proxy_send_timeout 30s;

        proxy_http_version 1.1;

        proxy_set_header Connection "";

        proxy_hide_header X-Frame-Options;

        add_header Access-Control-Allow-Origin *;

    }

    access_log  /www/wwwlogs/wst.77gwy.cn.log;

    error_log  /www/wwwlogs/wst.77gwy.cn.error.log;

}

微信小程序端

从列表页触发,然后在webview显示

列表页如下


packageE\onlineServices\onlineServices.wxml

<topbarPage>在线办事</topbarPage>
<view class="all">
    <view class="content">
        <view class="search">
            <van-search value="{{ value }}" placeholder="请输入搜索关键词" background="#4fc08d00"/>
        </view>
        <!-- 图片+文字容器:相对定位,作为文字绝对定位的参考 -->
        <view class="img-text-container">
            <view class="img-text-item" wx:for="{{ onlineServices }}" wx:key="id" bindtap="onItemClick" data-url="{{ item.url }}">
                <!-- 背景图片 -->
                <image
                    class="bg-img"
                    src="{{ item.img }}"
                    mode="widthFix"
                    lazy-load
                ></image>
                <!-- 叠加的文字 -->
                <view class="overlay-text">{{ item.name }}</view>
            </view>
        </view>
    </view>
</view>

packageE\onlineServices\onlineServices.js

// packageE/onlineServices/onlineServices.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        value: '',
        onlineServices: [
            {
                id: 1,
                name: '被征地农民养老保险待遇办理',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/5hSV4cTsUErCf49f5cf58c3046f983e61577f509b50c_20251209133727A993.png',
                url: 'https://hf.ahzwfw.gov.cn/bog-bsdt/static/workProcess/components/applicationMaterial.html?ssqdCode=128ea26c56a141be8bc9472ffbaec16f',
            },
            {
                id: 2,
                name: '带病回乡退伍军人认定',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/CQw6oxbhNlgff020d8f0a0fe6381f62ce5e352626ed7_20251209133816A994.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 3,
                name: '独生子女父母光荣证办理和补办',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/fQXZr1yBR7Mi6a8efa95ce70af7d4a424706655bb673_20251209133833A995.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 4,
                name: '劳动人事争议调解申请',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/mhizoAq52BgZfe37fa9c103769df4f728ad8c2a0af09_20251209133843A996.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 5,
                name: '烈士、因公牺牲军人、病故军人的子女、兄弟姐...',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/fZujlsqJ8iEkf49f5cf58c3046f983e61577f509b50c_20251209133852A997.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 6,
                name: '烈士安葬服务',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/S2X8KWGG14dB45f6783d84635e2d1e83cfd7465bb0e1_20251209133901A998.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 7,
                name: '领取独生子女父母光荣证的企业退休职工一次性….',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/0q1K5BMMxqk62044f1cfe665fb6bf9a19f56a1173643_20251209133910A999.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 8,
                name: '生育登记服务',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/5hSV4cTsUErCf49f5cf58c3046f983e61577f509b50c_20251209133727A993.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 9,
                name: '图鷓垡自书紓人再仍馆办证(补证)服务',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/CQw6oxbhNlgff020d8f0a0fe6381f62ce5e352626ed7_20251209133816A994.png',
                url: 'https://www.baidu.com',
            },
            {
                id: 10,
                name: '乡村建设规划许可(村民自建住宅)',
                img: 'https://chms.qmkjzh.com/file/statics/2025/12/09/fQXZr1yBR7Mi6a8efa95ce70af7d4a424706655bb673_20251209133833A995.png',
                url: 'https://www.baidu.com',
            },
        ],
    },
    onChange(e) {
        this.setData({
        value: e.detail,
        });
    },
    onSearch() {
        Toast('搜索' + this.data.value);
    },
    onClick() {
        Toast('搜索' + this.data.value);
    },
   
    /**
     * 点击办事项事件处理
     */
    onItemClick(e) {
        const url = e.currentTarget.dataset.url;
        if (url) {
            // 使用新创建的 webView 页面来加载 URL
            wx.navigateTo({
                url: `/packageE/webView/webView?url=${encodeURIComponent(url)}`
            });
        }
    },
   

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})
webview显示页

packageE\webView\webView.wxml

<!--packageE/webView/webView.wxml-->
<web-view src="{{url}}"/>
packageE\webView\webView.js

// packageE/webView/webView.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        url: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {      
        let url = '';
       
        // 优先使用URL参数
        if (options.url) {
            url = decodeURIComponent(options.url);
        }
       
        // 根据Nginx代理规则转换URL
        // 将外部链接转换为代理链接格式:https://proxy.xxx.com/forward/目标路径
        let proxyUrl = url;
        try {
            // 在微信小程序环境中,URL构造函数可能不被支持,使用正则表达式解析
            // 匹配URL的路径和查询参数部分
            const urlPattern = /^(https?:\/\/[^/]+)(.*)$/;
            const match = url.match(urlPattern);
            if (match && match[2]) {
                // 提取路径和查询参数
                const path = match[2];
                // 替换为代理域名和转发路径
                // 注意:这里的代理域名需要替换为实际已配置的自有域名
                proxyUrl = `https://wst.77gwy.cn/forward${path}`;
            }
        } catch (e) {
            console.error('URL解析失败:', e);
        }
       
        console.log('Original URL:', url);
        console.log('Proxy URL:', proxyUrl);
        this.setData({
            url: proxyUrl
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})
18455111359 扫描二维码