在个人网站上,总是倾向于在锚中使用相对路径,以便您可以轻松地将您的目录结构移动到一个新网站,但我希望使我的部分网站密码受到保护(使用.htaccess),从而使用https。在锚的href中是否有一种方法可以指定不同的协议,而不需要硬编码www.domain.com
呢?
示例:
<a href="/student/example">Link</a>
我想把它变成这样:
<a href="https: /student/example">Link</a>
以上这些显然不起作用。有什么办法吗?我试图避免任何脚本,但会更喜欢JavaScript比PHP或ASP。
发布于 2013-06-12 00:14:17
如果不依赖Javascript动态更改href,就无法做到这一点。相对URI转换为绝对URI的方式用RFC 3986第5.2.2节描述。
if defined(R.scheme) then
T.scheme = R.scheme;
T.authority = R.authority;
T.path = remove_dot_segments(R.path);
T.query = R.query;
else
if defined(R.authority) then
T.authority = R.authority;
T.path = remove_dot_segments(R.path);
T.query = R.query;
else
if (R.path == "") then
T.path = Base.path;
if defined(R.query) then
T.query = R.query;
else
T.query = Base.query;
endif;
else
if (R.path starts-with "/") then
T.path = remove_dot_segments(R.path);
else
T.path = merge(Base.path, R.path);
T.path = remove_dot_segments(T.path);
endif;
T.query = R.query;
endif;
T.authority = Base.authority;
endif;
T.scheme = Base.scheme;
endif;
T.fragment = R.fragment;
其中R
是相对URL,T
是目标。
上面基本上说,如果方案是在相对uri中指定的,那么目标uri将是整个相对URI,因此指定该方案的唯一方法是指定整个url。
如果您想使用基于Javascript的方法,可以使用类似于:a.href = 'https://' + window.location.host + a.getAttribute('href')
的方法动态设置href。a
是你的AnchorElement。
以下是Javascript版本的演示:http://jsfiddle.net/7DWV5/
但是,主要由于您遇到的原因,最好要么将主机名存储在配置文件中,要么从前端控制器中的HTTP Host
头中检测到主机名。这样,您就可以在生成页面时将其模板到HTML中。这使您不必在生成urls后使用客户端脚本来修复urls,这可能是可取的,因为并非每个人都启用了Javascript。
发布于 2013-06-12 01:09:13
我认为没有“简单”的解决办法..。而javascript似乎是这样的一个坏主意。
你可以试试:
<base href="https://yourdomain.com/">
放置在文档标题中。
或
你的想法:
<a href="/test-me1/">regular link 1</a>
<a href="/test-me2/">regular link 2</a>
<a href="/https/test-me3/">secure link</a>
在底部,但在关闭body之前,标记放置如下所示:
<script type="text/javascript">
(function(){
var h = 'yourdomain.com';
/* could be replaced with something like window.location.host */
var a = document.links;
for (var c = 0; c < a.length; c++) {
var i = a[c].href.indexOf('/https/');
if(-1 !== i)
{
a[c].href = 'https://' + h + '/' + a[c].href.substring( i + 7 );
/* where 7 is a length of '/https/' */
}
}
})();
</script>
甚至简单地说:
<script type="text/javascript">
(function(){
var a = document.links;
for (var c = 0; c < a.length; c++) {
if(-1 !== a[c].href.indexOf('/https/') )
{
a[c].href = a[c].href.replace('/https/','').replace('http:','https:');
}
}
})();
</script>
发布于 2013-06-12 00:16:49
您也应该使用.htaccess将https添加到站点的特定URL中。确保您的.htaccess文件包括以下一行:
RewriteEngine on
然后尝试在它后面添加这一行:
RewriteRule "^/student(/.*)" "https://%{HTTP_HOST}$1" [R=301,L]
http://www.askapache.com/htaccess/ssl-example-usage-in-htaccess.html#redirect-urls-to-ssl
https://stackoverflow.com/questions/17055605
复制相似问题