网站建设

百度嵌入式站内搜索https化实践分享

Jager · 10月23日 · 2016年 · 1408次已读

百度站内嵌入式搜索,相信很多网站都已经用了有一段时间了。可惜在百度自己大力提倡网站 https 化的同时,百度的周边产品却自己打脸了,完全跟不上进度。百度嵌入式站内搜索https化实践分享

不得不说,百度这个嵌入式站内搜索给了网站更多的 DIY 遐想,让搜索更加贴合各种主题,原汁原味:百度嵌入式站内搜索https化实践分享

Ps:预览地址:https://zhang.ge/search.html ,怎么制作这里就不赘述了,请参考本站历史教程

这玩意好是好,但是不支持 https!不过,我们可以有多种办法来变相实现。比如,利用七牛将百度分享 https 化、利用七牛将百度打赏 https 化,貌似七牛无所不能哦?

这里,当然也是可以利用七牛来解决问题,但是我并不想“邯郸学步”,所以这里打算用 Nginx 来实现。

一、改造原理

Ps:只求结果,不求过程的朋友请忽略此段啰嗦内容!

由于百度站内嵌入式搜索不支持 https,那么就算把主 js(iframe.js)本地化或者七牛化,也只是这一个文件实现了 https!从这个 js 加载出来的图片等各种资源却还是调用的百度的 http 资源!因此,我们得分析这个 js 会调用的资源,然后全部 https 化。

百度嵌入式搜索其实就一个主 js:http://zhannei.baidu.com/static/js/iframe.js,我们把它下载到本地,然后将其中的百度静态域名全部清空,只保留相对路径。比如:http://zhannei.baidu.com/customer_search/***,我们需要删除协议和域名部分,改成 /customer_search/*** 这种相对路径,这样我们才可以实现 Nginx 反代,七牛也是一样原理。

可能,光从肉眼去看 js 具体调用了哪些静态资源是比较困难苦逼的,这是我们可以将 js 上传到本地,然后将百度嵌入式代码改成本地 js,刷新前台的时候就可以在 F12 控制台去看某某资源因为不是 https 被拦截了,这样就知道哪些资源还需要继续改造了!

二、改造代码

既然分享,说明第一步的苦逼工作也已经做过了,直接分享代码:

!function(){function h(a,b){var c;for(c in b)b.hasOwnProperty(c)&&(a.style[c]=b[c])}function i(a,b){var d,c=a||{};for(d in b)b.hasOwnProperty(d)&&(c[d]=b[d]);return c}function j(){return/AppleWebKit.*Mobile/i.test(navigator.userAgent)||/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent)?1:0}function k(a,b,c){var f,g,h,i,j,d={},e=a.split(b);for(f=0;f<e.length;f++)g=e[f],h=g.indexOf(c),h>0&&(i=g.substring(0,h).toLowerCase(),j=g.substring(h+1,g.length),"q"!==i&&(j=encodeURIComponent(j)),d[i]=j);return d}function l(){var k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,a={},b=window.bdcsFrameResultNum?window.bdcsFrameResultNum:3,c=window.bdcsFrameCharset?window.bdcsFrameCharset:"utf-8",d=void 0!==window.bdcsRecommend?window.bdcsRecommend:0,e=window.bdcsDefaultQuery?window.bdcsDefaultQuery:0,h=window.bdcsDefaultQueryNum?window.bdcsDefaultQueryNum:1,i=void 0!==window.bdcsFramePos?window.bdcsFramePos:2,j=window.bdcsRemoveEm?window.bdcsRemoveEm:0;if(g&&(a.pg=g.replace("#","")),parseInt(b)&&(a.pn=parseInt(b)),("gbk"===c.toLowerCase()||"gb2312"===c.toLowerCase())&&(a.ie=c.toLowerCase()),1===d){if(a.rec=1,k=document.referrer){if(n={},decodeURIComponent(k)&&(l=decodeURIComponent(k)),m=l.split("?"),m[1])for(o=m[1].split("&"),p=0;p<o.length;p++)q=o[p].split("=")[0],r=o[p].split("=")[1],q&&r&&(n[q]=r);s=/www\.baidu\.com/,t=/m\.baidu\.com/,u=/cse\/search/,s.test(l)&&n["eqid"]?(a.eqid=n["eqid"],a.qfrom=1):(s.test(l)||t.test(l))&&n["word"]?(a.q=n["word"],a.qfrom=1):u.test(l)&&n["q"]&&(a.q=encodeURIComponent(n["q"]),a.qfrom=2)}if(0===e){if(!a.q||""===a.q){for(v=document.getElementsByTagName("meta"),w="",x=[],y=[],p=0;p<v.length;p++)v[p].getAttribute("name")&&v[p].getAttribute("content")&&"keywords"===v[p].getAttribute("name").toLowerCase()&&(x=v[p].getAttribute("content").split(/,| |、|;|,/));if(x.length>0){for(p=0;p<x.length;p++)""!==x[p]&&y.push(x[p]);for(z=Math.min(y.length,h),A=0;z>A;A++)w=w+" "+y[A];1!==a.qfrom&&(a.qfrom=3)}""===w&&document.title&&(w=document.title,1!==a.qfrom&&(a.qfrom=4)),""!==w&&(a.q=encodeURIComponent(w))}}else a.q=encodeURIComponent(e)}else a.rec=0,e&&(a.q=encodeURIComponent(e));return a.reg=f?encodeURIComponent(f):"",a.fpos=1===i?1:2===i?2:0,a.rmem=1===j?1:0,a.isIframe=1,a}function m(){var l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,a={},b=window.bdcsFrameWt?window.bdcsFrameWt:1,c=window.bdcsFrameHt?window.bdcsFrameHt:1,d=window.bdcsFrameResultNum?window.bdcsFrameResultNum:10,e=window.bdcsFrameCharset?window.bdcsFrameCharset:"utf-8",g=window.bdcsRecommend?window.bdcsRecommend:0,h=window.bdcsDefaultQuery?window.bdcsDefaultQuery:0,i=window.bdcsDefaultQueryNum?window.bdcsDefaultQueryNum:1,j=void 0!==window.bdcsFramePos?window.bdcsFramePos:2,k=window.bdcsRemoveEm?window.bdcsRemoveEm:0;if(a.wt=parseInt(b,10)>0&&parseInt(b,10)<4?parseInt(b,10):1,a.ht=parseInt(c,10)>0&&parseInt(c,10)<4?parseInt(c,10):1,parseInt(d,10)&&(a.pn=parseInt(d,10)),("gbk"===e.toLowerCase()||"gb2312"===e.toLowerCase())&&(a.ie=e.toLowerCase()),1===g){if(a.rec=1,l=document.referrer){if(o={},decodeURIComponent(l)&&(m=decodeURIComponent(l)),n=m.split("?"),n[1])for(p=n[1].split("&"),q=0;q<p.length;q++)r=p[q].split("=")[0],s=p[q].split("=")[1],r&&s&&(o[r]=s);t=/www\.baidu\.com/,u=/cse\/search/,t.test(m)&&o["eqid"]?(a.eqid=o["eqid"],a.qfrom=1):u.test(m)&&o["q"]&&(a.q=encodeURIComponent(o["q"]),a.qfrom=2)}if(0===h){if(!a.q||""===a.q){for(v=document.getElementsByTagName("meta"),w="",x=[],y=[],q=0;q<v.length;q++)v[q].getAttribute("name")&&v[q].getAttribute("content")&&"keywords"===v[q].getAttribute("name").toLowerCase()&&(x=v[q].getAttribute("content").split(/,| |、|;|,/));if(x.length>0){for(q=0;q<x.length;q++)""!==x[q]&&y.push(x[q]);for(z=Math.min(y.length,i),A=0;z>A;A++)w=w+" "+y[A];1!==a.qfrom&&(a.qfrom=3)}""===w&&document.title&&(w=document.title,1!==a.qfrom&&(a.qfrom=4)),""!==w&&(a.q=encodeURIComponent(w))}}else a.q=encodeURIComponent(h)}else h&&(a.q=encodeURIComponent(h));return a.fpos=1===j?1:2===j?2:0,a.rmem=1===k?1:0,a.reg=f?encodeURIComponent(f):"",a}function n(a){var f,c=b;c=c+"?"+"s="+d+"&loc="+encodeURIComponent(window.location.href)+"&width="+e;for(f in a)c=c+"&"+encodeURIComponent(f)+"="+a[f];return c}function o(){var f,o,q,r,s,t,u,v,w,x,b=document.getElementById("bdcs-frame-box"),c=j()?l():m();if(4===c.qfrom&&""!==document.title)f={title:document.title,locUrl:window.location.href},o="",a.init(),a.get({url:"/api/customsearch/keywords",parameters:f,success:function(a){var f,l,m,q,r,s,t,u,v,w,x,y;if(a&&a.result&&a.result.res&&a.result.res.keyword_list)for(f=a.result.res.keyword_list,l=Math.min(f.length,3),m=["single","single","single"],a.result.res.keyword_type_list&&(m=a.result.res.keyword_type_list),q=0;l>q&&(o=o+" "+f[q],0!==q||"combine"!==m[0])&&!(l-1>q&&"combine"===m[q+1]);q++);if(c.qfrom=5,c.q=o,""===o&&(c.q=document.title,c.qfrom=4),r=window.location.search.substring(1),s=k(r,"&","="),t={},s.q&&""!==s.q&&(t.q=s.q),s=i(s,c),s=i(s,t),u=n(s),v={name:"bdcsFrame",id:"bdcsFrame",src:u,frameBorder:"0",width:"100%",height:"100%",marginWidth:"0",marginHeight:"0",hspace:"0",vspace:"0",allowTransparency:"true",scrolling:"no"},b&&u&&""!==d){1===j()?h(b,{width:"100%",height:"auto",backgroundColor:g}):h(b,{width:e+"px",height:"auto",backgroundColor:g}),w=document.createElement("iframe");for(x in v)w.setAttribute(x,v[x]);b.appendChild(w),y=window.bdcsRecommend?window.bdcsRecommend:0,window.postMessage&&(window.attachEvent?window.attachEvent("onmessage",function(a){if(0===parseInt(a.data,10))w.height="100%",document.getElementById("bdcsFrame").contentWindow.postMessage("getHeight","*");else if(a.data.toString().indexOf("px")<0&&a.data.toString().indexOf("none")<0){var b=parseInt(a.data,10)+10;isNaN(b)||(w.height=b+"px")}}):window.addEventListener("message",function(a){if(0===parseInt(a.data,10))w.height="100%",document.getElementById("bdcsFrame").contentWindow.postMessage("getHeight","*");else if(a.data.toString().indexOf("px")<0&&a.data.toString().indexOf("none")<0){var b=parseInt(a.data,10)+10;isNaN(b)||(w.height=b+"px")}},!1)),w.attachEvent?w.attachEvent("onload",function(){y||(window.scrollTo(0,0),window.parent.window.scrollTo(0,0)),window.postMessage||p(w,b)}):w.addEventListener("load",function(){y||(window.scrollTo(0,0),window.parent.window.scrollTo(0,0)),window.postMessage||p(w,b)},!1)}}});else if(q=window.location.search.substring(1),r=k(q,"&","="),s={},r.q&&""!==r.q&&(s.q=r.q),r=i(r,c),r=i(r,s),t=n(r),u={name:"bdcsFrame",id:"bdcsFrame",src:t,frameBorder:"0",width:"100%",height:"100%",marginWidth:"0",marginHeight:"0",hspace:"0",vspace:"0",allowTransparency:"true",scrolling:"no"},b&&t&&""!==d){1===j()?h(b,{width:"100%",height:"auto",backgroundColor:g}):h(b,{width:e+"px",height:"auto",backgroundColor:g}),v=document.createElement("iframe");for(w in u)v.setAttribute(w,u[w]);b.appendChild(v),x=window.bdcsRecommend?window.bdcsRecommend:0,window.postMessage&&(window.attachEvent?window.attachEvent("onmessage",function(a){if(0===parseInt(a.data,10))v.height="100%",document.getElementById("bdcsFrame").contentWindow.postMessage("getHeight","*");else if(a.data.toString().indexOf("px")<0&&a.data.toString().indexOf("none")<0){var b=parseInt(a.data,10)+10;isNaN(b)||(v.height=b+"px")}}):window.addEventListener("message",function(a){if(0===parseInt(a.data,10))v.height="100%",document.getElementById("bdcsFrame").contentWindow.postMessage("getHeight","*");else if(a.data.toString().indexOf("px")<0&&a.data.toString().indexOf("none")<0){var b=parseInt(a.data,10)+10;isNaN(b)||(v.height=b+"px")}},!1)),v.attachEvent?v.attachEvent("onload",function(){x||(window.scrollTo(0,0),window.parent.window.scrollTo(0,0)),window.postMessage||p(v,b)}):v.addEventListener("load",function(){x||(window.scrollTo(0,0),window.parent.window.scrollTo(0,0)),window.postMessage||p(v,b)},!1)}}function p(a){if(""!==window.name&&0===j()){var c=parseInt(window.name)+10;a.height=c+"px"}}function q(a,b){var c=b,d=b;return a.style.inlineName?a.style[c]:document.defaultView&&document.defaultView.getComputedStyle?document.defaultView.getComputedStyle(a,null).getPropertyValue(d):a.currentStyle?a.currentStyle[c]:null}function r(a,b){var c,d,e,f,g;if(b=b||document,b.getElementsByClassName)return b.getElementsByClassName(a);for(c=[],d=b.getElementsByTagName("*"),e=new RegExp("(^|\\s)"+a.replace(/\-/g,"\\-")+"(\\s|$)"),f=0,g=d.length;g>f;f++)e.test(d[f].className)&&c.push(d[f]);return c}function s(a,b,c){document.addEventListener?a.addEventListener(b,c,!1):document.attachEvent&&a.attachEvent("on"+b,function(b){b.preventDefault=function(){b.returnValue=!1},b.stopPropagation=function(){b.cancelBubble=!0},c.call(a,b)})}function w(a,b,c){var d,e,f,g;b=b===!1?!1:!0,c=c||"bdcs-styleElem",b&&(a=(a||"").replace(u,".bdcs-container .bdcs-")),d=document.getElementById("znBdcsStyle"),d?d.styleSheet?(v.push(a),d.styleSheet.cssText=v.join("\n")):d.appendChild(document.createTextNode(a)):(e=document.createElement("style"),e.id="znBdcsStyle",e.rel="stylesheet",e.type="text/css",f=document.getElementsByTagName("head"),f&&(g=f[0],g.children[0]?g.insertBefore(e,g.children[0]):g.appendChild(e)),e.styleSheet?(e.styleSheet.cssText=a,v.push(a)):e.appendChild(document.createTextNode(a)))}var t,u,v,x,y,z,a=function(a){"use strict";var b,c,d,e,f,g,h,i,j;return c=function(a,b,c){a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent?a.attachEvent("on"+b,c):a["on"+b]=c},d=function(c,d){b.log("Garbage collecting!"),d.parentNode.removeChild(d),a[c]=void 0;try{delete a[c]}catch(e){}},e=function(a,b){var d,e,c="";for(d in a)a.hasOwnProperty(d)&&(d=b?encodeURIComponent(d):d,e=b?encodeURIComponent(a[d]):a[d],c+=d+"="+e+"&");return c.replace(/&$/,"")},f=function(){var a="",b=[],c="0123456789ABCDEF",d=0;for(d=0;32>d;d+=1)b[d]=c.substr(Math.floor(16*Math.random()),1);return b[12]="4",b[16]=c.substr(8|3&b[16],1),a="flyjsonp_"+b.join("")},g=function(a,c){b.log(c),"undefined"!=typeof a&&a(c)},h=function(a,c){b.log("GET success"),"undefined"!=typeof a&&a(c),b.log(c)},i=function(a,c){b.log("POST success"),"undefined"!=typeof a&&a(c),b.log(c)},j=function(a){b.log("Request complete"),"undefined"!=typeof a&&a()},b={},b.options={debug:!1},b.init=function(a){var c;b.log("Initializing!");for(c in a)a.hasOwnProperty(c)&&(b.options[c]=a[c]);return b.log("Initialization options"),b.log(b.options),!0},b.log=function(c){a.console&&b.options.debug&&a.console.log(c)},b.get=function(k){k=k||{};var l=k.url,m=k.callbackParameter||"callback",n=k.parameters||{},o=a.document.createElement("script"),p=f(),q="?";if(!l)throw new Error("URL must be specified!");n[m]=p,l.indexOf("?")>=0&&(q="&"),l+=q+e(n,!0),a[p]=function(a){"undefined"==typeof a?g(k.error,"Invalid JSON data returned"):"post"===k.httpMethod?(a=a.query.results,a&&a.postresult?(a=a.postresult.json?a.postresult.json:a.postresult,i(k.success,a)):g(k.error,"Invalid JSON data returned")):h(k.success,a),d(p,o),j(k.complete)},b.log("Getting JSONP data"),o.setAttribute("src",l),o.setAttribute("charset","utf-8"),a.document.getElementsByTagName("head")[0].appendChild(o),c(o,"error",function(){d(p,o),j(k.complete),g(k.error,"Error while trying to access the URL")})},b.post=function(a){a=a||{};var f,g,c=a.url,d=a.parameters||{},h={};if(!c)throw new Error("URL must be specified!");f=encodeURIComponent('select * from jsonpost where url="'+c+'" and postdata="'+e(d,!1)+'"'),g="//query.yahooapis.com/v1/public/yql?q="+f+"&format=json"+"&env="+encodeURIComponent("store://datatables.org/alltableswithkeys"),h.url=g,h.httpMethod="post","undefined"!=typeof a.success&&(h.success=a.success),"undefined"!=typeof a.error&&(h.error=a.error),"undefined"!=typeof a.complete&&(h.complete=a.complete),b.get(h)},b}(window),b="/cse/search",c=new RegExp("^#[0-9a-fA-F]{6}$"),d=window.bdcsFrameSid?window.bdcsFrameSid.toString():"",e=window.bdcsFrameWidth?parseInt(window.bdcsFrameWidth,10):552,f=window.bdcsFrameReg?window.bdcsFrameReg:"",g=c.test(window.bdcsFrameBgColor)?window.bdcsFrameBgColor:"#ffffff";o(),t=function(){function a(a){var b="_rpLog-"+(new Date).getTime(),c=new Image;window[b]=c,c.onload=c.onerror=function(){window[b]=null},c.src=a,c=null}function b(a,b){var d,c=a||{};for(d in b)b.hasOwnProperty(d)&&(c[d]=b[d]);return c}function c(c){var i,k,l,f={logid:0,version:0,prod_id:"rp",plate_url:encodeURIComponent(window.location.href),referrer:encodeURIComponent(document.referrer),time:(new Date).getTime()},g=f,h=[],j=c;for("?"!==j.charAt(j.length-1)&&(j+="?"),k=1,l=arguments.length;l>k;k++)"[object Object]"===Object.prototype.toString.call(arguments[k])&&(g=b(g,arguments[k]));for(i in g)h.push(i+"="+g[i]);a(j+h.join("&")),"[object Function]"===Object.prototype.toString.call(arguments[arguments.length-1])&&arguments[arguments.length-1].call()}return{send:c}}(),u=/\.bdcs-/g,v=[],x='<div class="bcse-card-top">\n<span class="bcse-card-title">搜索到关于</span>\n<span class="bcse-card-query" title=""></span>\n<span class="bcse-card-title">的其他站内文章</span>\n<span class="bcse-card-close">×</span>\n</div>\n<div class="bcse-card-center">\n<iframe width="125" height="71" scrolling="no" class="bcse-card-frame" id="bdcsCardFrame" frameborder="0" src=""></iframe>\n<div class="bcse-card-result-title">\n<a class="bcse-card-first-link" href="" target="_blank" title="" cpos="1"></a>\n</div>\n<div class="bcse-card-result-abstract"></div>\n<div class="bcse-card-result-next">\n<a class="bcse-card-next-link" href="" target="_blank" title="" cpos="2"></a>\n</div>\n</div>\n',y="#bdcsWnCard{position:fixed;bottom:50px;left:0;width:326px;max-height:158px;box-shadow:2px 3px 3px #ccc;background-color:#fff;display:none;left:-328px;z-index:99999999;font-family:'Microsoft Yahei',微软雅黑,serif}#bdcsWnCard .bcse-card-top{width:316px;height:28px;line-height:28px;font-size:13px;color:#ebedfb;background-color:#2C85FF;padding-left:10px}#bdcsWnCard .bcse-card-title{float:left;display:inline-block}#bdcsWnCard .bcse-card-query{float:left;display:inline-block;font-weight:700;margin:0 3px;max-width:110px;overflow:hidden;white-space:nowrap;color:#fff;-o-text-overflow:ellipsis;text-overflow:ellipsis}#bdcsWnCard .bcse-card-close{float:right;font-size:22px;margin-right:5px;margin-top:-2px;cursor:pointer}#bdcsWnCard .bcse-card-center{padding:15px 10px}#bdcsWnCard .bcse-card-frame{float:left;height:75px;width:121px;margin-right:15px;margin-bottom:10px}#bdcsWnCard .bcse-card-result-title{word-break:break-all;line-height:16px;max-height:33px;overflow:hidden}#bdcsWnCard .bcse-card-center a{font-size:14px;color:#333;text-decoration:none}#bdcsWnCard .bcse-card-result-title a:visited{color:#333}#bdcsWnCard .bcse-card-result-abstract{font-size:12px;word-break:break-all;color:#bfbfbf;height:28px;line-height:14px;margin-top:10px;overflow:hidden}#bdcsWnCard .bcse-card-result-next{font-size:14px;width:100%;line-height:16px;height:16px;overflow:hidden;color:#333;margin-top:15px}.clearfix:after{content:'';display:block;clear:both;height:0}.clearfix{zoom:1}",z=function(){function c(e){var h,f=document.getElementById("bdcsWnCard"),g=parseInt(q(f,"left"),10);0>g?(window.bdcsMncardReady=0,f.style.left=g+4+"px",window.setTimeout(function(){c(e)},1)):(window.bdcsMncardReady=1,a=1,b=0,t.send("/customer_search/click",h,{query:r("bcse-card-query")[0].getAttribute("title"),log_type:"wn-card-show",site_id:d,type:e,from:"iframe",plate_url:window.location.href}))}function e(){var c=document.getElementById("bdcsWnCard"),d=parseInt(q(c,"left"),10);d>-328?(window.bdcsMncardReady=0,c.style.left=d-4+"px",window.setTimeout(function(){e()},1)):(a=0,b=1,c.style.display="none",window.bdcsMncardReady=1)}function f(a){this.options=a,this.render(this.options.data,this.options.qType)}var a=1,b=1;return f.prototype.render=function(a,b){var c,e,f,g,h,i,j,k;w(y),c=document.createElement("div"),c.className="bcse-wn-card",c.id="bdcsWnCard",document.body.appendChild(c),c.innerHTML=x,e=r("bcse-card-query")[0],e.innerHTML=a["query"],e.setAttribute("title",a["query"]),f=r("bcse-card-first-link")[0],f.innerHTML=a["results"][0]["title"].replace(/<em>/g,"").replace(/<\/em>/g,""),f.setAttribute("title",a["results"][0]["title"].replace(/<em>/g,"").replace(/<\/em>/g,"")),f.setAttribute("href",a["results"][0]["url"]),g=r("bcse-card-next-link")[0],g.innerHTML=a["results"][1]["title"].replace(/<em>/g,"").replace(/<\/em>/g,""),g.setAttribute("title",a["results"][1]["title"].replace(/<em>/g,"").replace(/<\/em>/g,"")),g.setAttribute("href",a["results"][1]["url"]),h=r("bcse-card-result-abstract")[0],h.innerHTML=a["results"][0]["abstract"].replace(/<em>/g,"").replace(/<\/em>/g,""),i=document.getElementById("bdcsCardFrame"),a["results"][0]["img"]?i.setAttribute("src","/static/customer-search/html/wncard.html?a="+a["results"][0]["url"]+"&q="+r("bcse-card-query")[0].getAttribute("title")+"&s="+d+"&p="+window.location.href+"&t="+b+"#"+a["results"][0]["img"]):i.style.display="none",window.bdcsMncardMtd=1,window.bdcsMncardReady=1,j=document.documentElement.scrollTop||document.body.scrollTop,k=Math.max(document.documentElement.scrollHeight,document.body.clientHeight),j>=(k-document.documentElement.clientHeight)/2&&1===window.bdcsMncardMtd&&(document.getElementById("bdcsWnCard").style.display="block",document.getElementById("bdcsWnCard").style.left=0),this.bind(b)},f.prototype.bind=function(f){s(r("bcse-card-close")[0],"click",function(){document.getElementById("bdcsWnCard").style.display="none",window.bdcsMncardMtd=0}),window.onscroll=function(){var d=document.documentElement.scrollTop||document.body.scrollTop,g=Math.max(document.documentElement.scrollHeight,document.body.clientHeight),h=document.getElementById("bdcsWnCard");d>=(g-document.documentElement.clientHeight)/2&&1===window.bdcsMncardMtd&&1===window.bdcsMncardReady&&1===b?(h.style.display="block",c(f)):d<(g-document.documentElement.clientHeight)/2&&1===window.bdcsMncardReady&&1===a&&e()};for(var g=0;g<document.getElementById("bdcsWnCard").getElementsByTagName("a").length;g++)s(document.getElementById("bdcsWnCard").getElementsByTagName("a")[g],"click",function(){var c,b=this.getAttribute("href");t.send("/customer_search/click",c,{query:r("bcse-card-query")[0].getAttribute("title"),url:b,log_type:"wn-card-click",site_id:d,plate_url:window.location.href,type:f,from:"iframe",cpos:this.getAttribute("cpos")?this.getAttribute("cpos"):3})})},f}(),function(){var g,i,k,l,m,n,o,p,q,r,s,t,u,v,w,b=[],c=[],e=0,f={s:d,locUrl:window.location.href},h=document.referrer;if(h){if(l={},decodeURIComponent(h)&&(i=decodeURIComponent(h)),k=i.split("?"),k[1])for(m=k[1].split("&"),n=0;n<m.length;n++)o=m[n].split("=")[0],p=m[n].split("=")[1],o&&p&&(l[o]=p);q=/www\.baidu\.com/,r=/cse\/search/,q.test(i)&&l["eqid"]?(f["eqid"]=l["eqid"],g=1):r.test(i)&&l["q"]&&(f["q"]=l["q"],g=2)}if(!f["q"]){for(s=document.getElementsByTagName("meta"),t="",u=[],v=[],n=0;n<s.length;n++)s[n].getAttribute("name")&&s[n].getAttribute("content")&&"keywords"===s[n].getAttribute("name").toLowerCase()&&(u=s[n].getAttribute("content").split(/,| |、|;|,/));if(u.length>0){for(n=0;n<u.length;n++)""!==u[n]&&v.push(u[n]);v.length>0&&(t=v[0],1!==g&&(g=3))}""===t&&document.title&&(t=document.title,1!==g&&(g=4)),""!==t&&(f["q"]=t)}for(w=0;w<c.length;w++)window.location.href===c[w]&&(e=1);for(n=0;n<b.length;n++)window.location.href.indexOf(b[n])>=0&&0===e&&0===j()&&!document.getElementById("bdcsWnCard")&&(f["q"]||f["eqid"])&&(a.init(),a.get({url:"/api/customsearch/search",parameters:f,success:function(a){a&&0===a.error&&a.results.length>1&&new z({data:a,qType:g})}}))}()}();

将以上代码保存为 js 文件,比如 baidusearch.js ,然后上传到服务器网站目录,(推荐放于主题下,比如:/wp-content/themes/begin/js/baidusearch.js)

然后,将百度站内嵌入式搜索代码中的 iframe.js 地址替换为以上 js 地址,到此完成网站代码部分改造:

<div id="bdcs-frame-box"></div>
<script type="text/javascript">
var bdcsFrameSid="此处填写你的百度站内搜索 ID";
var bdcsFrameCharset= "utf-8";
var bdcsFrameWidth = 650; //宽度请自行调整
var bdcsFrameHeight = 0;
var bdcsFrameWt = 1;
var bdcsFrameHt = 2;
var bdcsFrameResultNum = 20;
var bdcsFrameBgColor = "#fff";
var bdcsRecommend = 0;
var bdcsDefaultQuery = 0;
var bdcsRemoveUrl = 0;
</script>
<!-- 按照实际情况修改下面 js 地址 -->
<script type="text/javascript" src="/wp-content/themes/begin/js/baidusearch.js"></script>

Ps:更多内容,请参考本站历史教程

三、反向代理

第二步还只是将相关资源全部指向了本地,所以下面需要改造 Nginx,将这些指向全部反代到百度站内搜索,修改很简单,将以下 Nginx 代码添加到网站 Nginx 配置的 location / { 之前:

    location ~* /static/img/ {
        proxy_pass http://zhannei.baidu.com;
        proxy_redirect off;
        #支持 purge 缓存的环境可以取消以下三行注释,让资源缓存到服务器,注意 cache_one 改成实际名称
        #proxy_cache cache_one;
        #proxy_cache_valid 200 302 304 7d;
        #proxy_cache_valid any 1m;
    }
    
    location ~* ^/(cse|static|api) {
        proxy_pass http://zhannei.baidu.com;
        proxy_redirect off;
        #支持 purge 缓存的环境可以取消以下三行注释,让资源缓存到服务器,注意 cache_one 改成实际名称
        #proxy_cache cache_one;
        #proxy_cache_valid 200 302 304 7d;
        #proxy_cache_valid any 1m;
        expires max; 
    }

    location ~* "customer(.+)search" {
        proxy_pass http://znsv.baidu.com;
        proxy_redirect off;
        #支持 purge 缓存的环境可以取消以下三行注释,让资源缓存到服务器,注意 cache_one 改成实际名称
        #proxy_cache cache_one;
        #proxy_cache_valid 200 302 304 7d;
        #proxy_cache_valid any 1m;
        expires max;

        }

如果,Nginx 集成了 ngx_cache_purge 缓存模块,那么可以将上述代码中的缓存规则打开,避免每次搜索还要到百度去请求资源【相关教程】!

规则添加后,重启或重载 Nginx 即可生效。这时候,https 前台就能正常使用百度嵌入式站内搜索了!

四、更多花絮

https 实现了,但是还是有些瑕疵,那就是搜索结果中缩略图默认使用 https 协议,可能会被浏览器拦截。在张戈博客应用这个改造后,发现大部分缩略图居然返回 403 禁止了,仔细看了下,大部分如下形式:

http://i8.baidu.com/it/u=1582249672,3936911246&fm=85&s=6BAAA3475C1300C649B5710B0100E09

看来是百度站内搜索 zhannei.baidu.com开启了防盗链机制,自己不支持 https,还不让别人改造么?于是直接给站内搜索管理员发了一份邮件:百度嵌入式站内搜索https化实践分享

目前,站内搜索确实取消防盗链了,虽然管理员牛逼哄哄的也没回我邮件。。。

虽然不再禁止访问了,但里面的图片依然是 http 协议的,严格的浏览器还是会禁止加载,不过对于完全不能用来说,这个瑕疵还算可以忍受!

58 条回应
  1. 憧憬Licoy 2016-10-23 · 16:17

    够折腾

  2. 龙笑天 2016-10-23 · 16:43

    [color=green]百度收录的文章太少了,我就换成了360搜索了~~[/color] :razz:
    PS:你的滑动解锁在我的Firefox 28上解锁后不提及评论,停在那了~~!

    • 热腾网 2016-10-25 · 9:28

      用百度的还是多。

  3. 网赚博客 2016-10-23 · 16:55

    多谢分享

  4. 老周博客 2016-10-23 · 21:20

    不错的技术博客,受益匪浅,多谢分享!

  5. chencool 2016-10-24 · 11:29

    收了,谢谢博主!! :idea:

  6. 购物街 2016-10-24 · 16:12

    谢谢分享

  7. suppore 2016-10-24 · 23:17

    很不错的,来学习下。

  8. RaresNote 2016-10-25 · 8:35

    安全技术型啊,赞!

  9. 禾元商用豆花机 2016-10-25 · 10:54

    很好的博客,多学习很多东西

  10. 德国莱默尔E+L 2016-10-25 · 21:14

    网站重定向后关键字排名下降了50名之外

  11. 千博地方门户系统 2016-10-25 · 22:53

    用百度的还是多。

  12. 下拉通刷词软件 2016-10-26 · 16:15

    这个切入式的这样着实有点麻烦了

  13. 崛企科技 2016-10-26 · 16:48

    很复杂的样子

  14. 易淘金股票博客 2016-10-26 · 19:36

    好方法!!!!!!!!!!!!!!!!!!!!!

  15. 乐赚鸟 2016-10-26 · 19:40

    签到成功!签到时间:下午7:39:01,每日签到,生活更精彩哦~

    [color=red]评论不显示,是神马问题 :sad: [/color]

  16. 小萝博客 2016-10-27 · 13:33

    又可以折腾一下咯

  17. themebetter 2016-10-28 · 16:50

    生活的乐趣在于折腾。

  18. 微部落博客 2016-10-29 · 18:50

    百度最近收录持续减少,不知道哪里又抽风了

  19. 彭挺 2016-10-30 · 14:20

    看着头疼签到成功!签到时间:下午2:20:17,每日签到,生活更精彩哦~

  20. 何湘辉博客 2016-10-30 · 21:26

    建议代码多的弄成附件下载,影响阅读体验

  21. 安康人才网 2016-11-1 · 10:55

    阅读后受益匪浅!

  22. 微部落博客 2016-11-2 · 18:56

    不要盯着百度搞,现在360搜索越多越多了

  23. 今日秀 2016-11-3 · 9:49

    这文章不错 我是一个刚刚涉足做网站这一块 各位大神 多多关照

  24. 励志语录 2016-11-4 · 19:48

    学习了,给力 :oops: 签到成功!签到时间:下午7:47:28,每日签到,生活更精彩哦~

  25. 靠谱学生兼职网 2016-11-8 · 12:09

    看到代码就有点头痛,还是用程序自身的搜索吧。

  26. 微部落博客 2016-11-9 · 13:41

    好多代码,看着就觉得很难。。

  27. 任务易 2016-11-9 · 14:37

    好杂,建议博主把排版改一下,视觉体验不是很好

    • avatar
      Jager 2016-11-9 · 22:58

      不觉得

  28. 神猪 2016-11-9 · 16:29

    嗯,chrome默认打开图就是裂的,而且百度收录你的页面90%都是http,你不是早就强制https了吗?怎么会这样?

    • avatar
      Jager 2016-11-9 · 22:59

      缩略图和https收录没关系,是百度自家没展示https

  29. 求学的小学生 2016-11-9 · 22:54

    http://bbs.zhanzhang.baidu.com/thread-133937-1-1.html 嘿嘿。似乎是新技术诶,Jager同学有没有关注一下呢?

    • avatar
      Jager 2016-11-9 · 22:59

      看了下,暂时没打算折腾。百度自己的规范而已

  30. 靠谱学生兼职网 2016-11-10 · 12:04

    很方便、很实用

  31. 赵庆福博客 2016-11-21 · 17:23

    因为看不懂,所以看不懂。 :mrgreen:

  32. 小哥网赚博客 2016-11-22 · 14:43

    细节很多 谢谢分享

  33. 夏日博客 2016-11-23 · 13:52

    懒得折腾了,直接把百度站内搜索给去掉了。

  34. 留笔记 2016-11-23 · 13:58

    Jager大大 你的搜索框不显示图片了

  35. 杨永博客 2016-11-23 · 19:15

    不ttps会有什么影响呢?

  36. 任务易 2016-11-30 · 13:19

    成功get~

  37. 信阳毛尖 2016-12-2 · 17:52

    可惜的是我已经取消了SSL的支持,百度统计依然不完善。

  38. 钟祥大美猫 2016-12-14 · 12:20

    这留言 打字的效果,,,怎德一个酷字了得。。

  39. 七弦琴 2017-2-7 · 19:43

    百度相关服务太坑了,想了想,还是取消掉百度站内了,就用默认的

  40. 狂放 2017-6-18 · 12:21

    可是图片是http还是会拦截

  41. 9号 2017-6-23 · 21:16

    百度站内搜索做的不错的

  42. 技术宅 2017-8-18 · 22:59

    我发现操作之后ssl提示有不安全的链接,打开一看,原来是缩略图用的还是http链接,看博主的加载资源中,缩略图是ssl格式的,比如你这边显示的是[color=red]https[/color]://i8.baidu.com/it/u=1867108336,3600725071&fm=85&s=0490ED32957075201EDDEDDE0300C0B1,我这边显示的却是[color=red]http[/color]://i8.baidu.com/it/u=1867108336,3600725071&fm=85&s=0490ED32957075201EDDEDDE0300C0B1

  43. 狂放 2017-9-24 · 15:45

    试着用php反代了,似乎TM防盗链又回来了

  44. 明月登楼 2018-3-7 · 11:00

    感觉百度除了“装逼”就是“装逼”!

  45. 差一撇 2019-1-13 · 11:16

    使用这个方式,但是百度分享就没办法使用了。 :???:

  46. andywen 2019-3-13 · 17:36

    您好,看您的反代是Nginx版的,有Apache版的吗?折腾了半天,都没试成功。

    • avatar
      Jager 2019-3-15 · 10:31

      apache没去折腾过

  47. andywen 2019-3-14 · 14:49

    嗨,哥们,你那个search的页面失效了。能修复一下吗?

    • avatar
      Jager 2019-3-15 · 10:31

      应该好了

  48. 吴昊博客 2019-4-19 · 11:05

    搜索缩略图403的问题可以通过cname解决,解析个域名cname到百度,然后反向代理这个域名。
    我写了一篇新文章,通过input实现,可以看看:https://blog.whsir.com/post-4289.html
    :oops: :oops:

    • avatar
      Jager 2019-4-19 · 11:22

      666,你的文章可以考虑把嵌入式搜索也一起解决、分享下。目前好像没看到缩略图403了,https://zhang.ge/search.html

  49. puffbaby 2019-4-20 · 17:19

    大神按照你的这个步骤来,最后显示“zhannei.baidu.com 的响应时间过长”是什么情况呢?网站也是加密的。

  50. 11 2020-9-23 · 2:28