Home > Web Front-end > JS Tutorial > body text

JavaScript implements forced redirection to HTTPS page_javascript skills

WBOY
Release: 2016-05-16 15:56:15
Original
1212 people have browsed it

Sometimes it is necessary to force a web page to switch to HTTPS, even if the user has already accessed the HTTP version. The reason may be that you don't want users to use HTTP for access because it is not secure. It's very simple to do this. If you don't want to use PHP or Apache's mod_rewrite to do this, you can also use Javascript. The code is as follows:

<script type="text/javascript">
var targetProtocol = "https:";
if (window.location.protocol != targetProtocol)
 window.location.href = targetProtocol +
  window.location.href.substring(window.location.protocol.length);
</script>
Copy after login

Using this code, if the user visits such as http://leonax.net/…, he will be redirected to https://leonax.net/… .. If you want to do the opposite, that is, force HTTPS to redirect to HTTP, just change the value of targetProtocol to http. Isn't it very convenient?

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!