使用相对链接从https(反之亦然)链接到http的简短方法

时间:2009-02-25 00:19:41

标签: html http https

当我正在开发网站的安全部分(使用https输入特定页面或文件夹)时,普通页面的相对链接会自动转换为https同样。

有没有办法告诉< a>标签总是使用http协议而不是https协议(或其他方式)?

我知道使用完整链接(http://www.mysite.com/index.htmlhttps://www.mysite.com/index.html)很容易,但我希望它可以使用相对链接(index.html,.. / index.html等) )。

6 个答案:

答案 0 :(得分:29)

您可以使用以下语法使所有内部链接独立于协议:

<a href="//some/file/on/your/domain.php">link text</a>

而不是

<a href="some/file/on/your/domain.php">link text</a>

//将使链接尊重页面加载的任何协议。

答案 1 :(得分:10)

我们使用Apache mod_rewrite来控制是否通过http或https提供页面。以下是网站根目录.htaccess文件中的示例代码段:

# Redirect most reqests for https to http
RewriteRule ^https://www.example.com(.*) http://www.example.com$1 [R=301,NC]

# Allow some URIs to be https if requested
RewriteCond   %{SERVER_PORT}  ^443$
RewriteCond   %{REQUEST_URI}  !^/images/(.*)$
RewriteCond   %{REQUEST_URI}  !^/scripts/(.*)$
RewriteCond   %{REQUEST_URI}  !^/styles/(.*)$
RewriteCond   %{REQUEST_URI}  !^/store(.*)$
RewriteCond   %{REQUEST_URI}  !^/login.htm$
RewriteRule ^(.*) http://www.example.com/$1 [L,R]

# Force some URIs to be https only
RewriteCond   %{SERVER_PORT}  ^80$
RewriteRule ^store(.*) https://www.example.com/store$1 [L,R]

RewriteCond   %{SERVER_PORT}  ^80$
RewriteRule ^FormSanityKey.htm https://www.example.com/login$1 [L,R]

阅读所有相关内容:

http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html

答案 2 :(得分:4)

不确定这是否正是您所寻找的,但如果您正在使用Apache,则可以使用一种技巧来执行此操作:http://httpd.apache.org/docs/2.2/ssl/ssl_faq.html#relative

基本上,您将以下内容放在Apache配置文件中:

RewriteEngine on
RewriteRule ^/(.*):SSL$ https://%{SERVER_NAME}/$1 [R,L]
RewriteRule ^/(.*):NOSSL$ http://%{SERVER_NAME}/$1 [R,L]

然后将:SSL附加到您要强制HTTPS的任何链接(在网页中),并:NOSSL添加到您要强制常规HTTP的任何链接。

答案 3 :(得分:2)

听起来你想使用the BASE element

没有办法“告诉”一个Anchor是否使用特定协议,至少不使用该页面HEAD中的BASE元素。

您是否有理由在绝对链接上使用相对链接? This article讨论了使用HTTPS的相对链接的缺陷 - 可能会使您的网站被双重索引等等。

答案 4 :(得分:2)

由于您使用的是不同的协议,因此无法使用相对超链接执行此操作,这与链接到ftp位置没有什么不同。

答案 5 :(得分:0)

由于我们根据协议提供了不同的内容,并且我们不知道托管在何处,因此我使用此代码创建了指向当前索引页面的链接以指向https服务器。

  <a>Secure server
    <script>
      let url = new URL(window.location);
      url.protocol = 'https:';
      url.port = '443';
      document.currentScript.parentElement.href = url.toString();
    </script>
  </a>