我需要一个脚本(JavaScript或PHP而不是mod_rewrite),它可以在所有* subdomain.example.com链接上替换所有HTTPS到HTTP,但为example.com和www.example.com保留HTTPS。
例如:我想转
<a href="HTTPS://sub.example.com">My sub domain</a>
到
<a href="HTTP://sub.example.com">My sub domain</a>
*会有很多不同的子域......
答案 0 :(得分:1)
不需要jQuery的解决方案:
var as = document.getElementsByTagName('a') //get all a tags
var re = /^https:\/\/[\w\W]*(example.com)/i //http://*example.com
var reExcept = /^https:\/\/(www.)?(example.com)/i //filter https://www.example.com and http://example.com
for (var i=0; i<as.length; i++) {
href = as[i].getAttribute('href')
console.log('original href: ' + href)
if (!href || !re.test(href) || reExcept.test(href) )
continue //this href shouldn't be replaced
href = href.replace('https://', 'http://')
as[i].setAttribute('href', href)
console.log('replaced href: ' + as[i].getAttribute('href'))
}
在https://www.google.com/search?q=google通过控制台进行测试(在re和reExept中使用google.com而不是example.com)。似乎工作正常。
稍微冗长的版本:
var re = /^https:\/\/[\w\W]*(example.com)/i
var reExcept = /^https:\/\/(www.)?(example.com)/i
var as = document.getElementsByTagName('a')
for (var i=0; i<as.length; i++) {
href = as[i].getAttribute('href')
if ( !href || !re.test(href) || reExcept.test(href) )
continue
as[i].setAttribute('href', href.replace(/^https:\/\//i, 'http://'))
}
答案 1 :(得分:0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<a href="https://www.test.com" >Test 1 </a><br>
<a href="https://ftp.test.com" >Test 2 </a><br>
<a href="https://test.test.com" >Test 3 </a><br>
<script type="text/javascript">
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
}
else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
domain = domain.replace("www.", "");
return domain;
}
$("a").each(function(){
var url = $(this).attr("href");
var res = extractDomain( url );
var resSplit = res.split('.');
if( resSplit.length > 2 ){
$(this).attr("href", url.replace("https","http") );
}
});
</script>
答案 2 :(得分:0)
这是PHP的解决方案。它还包括 subsub.sub.example.com 等子子域和仅 example.com 的域名。
请注意,当您想在服务器端执行此操作时...
因此,对于(例如)证书与某些子域名不匹配而其他子域名匹配的情况,您不能使用服务器端解决方案。
<?php
$tochange = array(
'sub', 'sub1', 'test',
);
$hname = getenv("SERVER_NAME");
if (preg_match('/^(.*)(\.(.*?)\.(.*))$/s', $hname, $regs)) {
// $regs[1] contains subdomain name / names (also: *subsub.sub.domain.tld").
$encrypted = ((isset($_SERVER["HTTPS"])) && (strtoupper($_SERVER["HTTPS"]) == 'ON'));
if ($encrypted && (in_array($regs[1],$tochange))) {
$port = getenv("SERVER_PORT");
$query = ($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
$url = 'httpx://' . $hname . $_SERVER['SCRIPT_NAME'] . $query;
// Do a redirect
header("location: $url"); // redirect
// echo "$url<br >"; // for testing
}
}
?>