Html page to redirect http to https

21 способ перенаправления c http на https (redirect)

Очень много вопросов ходит вокруг данной темы. Как сделать свой сайт безопасным? Наша веб-студия mad design собрала все возможные варианты, какими пользуемся мы:

Первое, что необходимо сделать, это получить SSL-сертификат. Вы можете приобрести его или получить бесплатно у большинства компаний, которые предоставляют услуги хостинга.

Что такое SSL-сертификат и зачем он нужен:

Secure Sockets Layer (SSL) — это протокол безопасности, который используется веб-браузерами и веб-серверами для защиты данных пользователей при их передаче в сети Интернет. Он гарантирует безопасное соединение между сервером и браузером пользователя. Сертификаты SSL представляют собой небольшие файлы данных, которые связывают ключ шифрования с данными организации (или физического лица, в случае, если сертификат SSL выпускается на данные физического лица). При просмотре сайтов в веб-браузере SSL-сертификат обеспечивает безопасное соединение между веб-сервером и браузером, о чем свидетельствует наличие значка закрытого «зеленого» замка в адресной строке и префикса «https», с которого начинается адрес страницы. В первую очередь SSL-сертификат необходим интернет-магазинам, банкам, платежным системам и другим организациям, работающим с персональными данными, для защиты транзакций и предотвращения несанкционированного доступа к информации. Кроме того, сайты с SSL-сертификатами имеют преимущество в поисковой выдаче.

И так, сертификат куплен. Теперь нам необходимо, что бы наш ресурс с http://вашдомен.ru переходил автоматически на https://вашдомен.ru. Для этого необходимо все настройки и манипуляции произвести в файле «.htaccess», который располагается в корневой папке вашего сайта.

Вот все самые простые и популярные варианты настройки редиректа для разных сценариев:

Читайте также:  Включить xml в html

Чтобы ссылка на одну страницу перенаправляла на открытие другой, добавьте в файл .htaccess следующую строку:

  • Redirect 301 — инструкция, сообщающая, что страница перемещена постоянно;
  • http://example.com/index.html — адрес страницы, на которую происходит перенаправление.

При использовании 301 редиректа рейтинг сайта в поисковых системах сохраняется.

Аналогичный синтаксис простого редиректа в другом примере:

В примере ниже выполняется редирект с www.old-domain.ru на www.new-domain.ru:

RewriteEngine onRewriteCond % ^(www\.)?old-domain\.ru$RewriteRule ^(.*)$ http://www.new-domain.ru/$1 [R=301,L]

RewriteCond задает условие, при котором происходит выполнение правила, указанного в RewriteRule. Таким образом, при запросе любой страницы www.old-domain.ru или old-domain.ru будет осуществлен переход на адрес www.new-domain.ru.

Данное перенаправление также может быть выполнено двумя способами. В примерах осуществляется редирект с forum.example.ru на www.forum.example.ru.

Options +FollowSymLinksRewriteEngine OnRewriteCond % ^forum\.example\.ru$ [NC]RewriteRule ^(.*)$ http://www.forum.example.ru/$1 [R=301,L]

Способ 2 (в данном способе нет необходимости указания домена).

Options +FollowSymLinksRewriteEngine OnRewriteCond % !^www\.(.*) [NC]RewriteRule ^(.*)$ http://www.%/$1 [R=301,L]

В примерах осуществляется перенаправление с www.forum.example.ru на forum.example.ru.

Options +FollowSymLinksRewriteEngine onRewriteCond % ^www\.forum\.example\.ru$ [NC]RewriteRule ^(.*)$ http://forum.example.ru/$1 [R=301,L]

Options +FollowSymLinksRewriteEngine onRewriteCond % !^forum\.example\.ru$ [NC]RewriteRule ^(.*)$ http://forum.example.ru/$1 [R=301,L]

Перенаправление поддомена forum.example.ru в подкаталог forum:

RewriteEngine on RewriteBase / RewriteCond % ^forum\.example\.ru$ RewriteCond % !/forum/ RewriteRule ^(.*)$ /forum/$1[L]

Перенаправление поддомена www.forum.example.ru в подкаталог forum:

RewriteEngine onRewriteBase /RewriteCond % ^(www\.)?forum\.example\.ru$RewriteCond % !/forum/RewriteRule ^(.*)$ /forum/$1[L]

Такие перенаправления могут быть полезны, когда необходимо, чтобы тот или иной статический файл (.txt, .jpg, .pdf и многие другие расширения) обрабатывался Apache вместо Nginx.

Перенаправление на PHP-скрипт при обращении к несуществующему файлу robots.txt:

RewriteEngine onRewriteCond % ^(www\.)?example\.ru$RewriteCond % ^/robots.txt$RewriteRule ^(.*)$ /forum/script.php [R=301,L]

Перенаправление с несуществующего файла filename.jpg на необходимый статический файл (предварительно нужно переименовать filename.jpg — например, в filename.jpg2):

RewriteEngine onRewriteCond % ^(www\.)?example\.ru$RewriteCond % ^/filename.jpg$RewriteRule ^(.*)$ /directory/filename.jpg2 [R=301,L]

Вариант 1 (без дополнительных условий).

Вариант 2 (перенаправление с http://example.ru на https://example.ru).

RewriteEngine OnRewriteBase /RewriteCond % !1RewriteCond % ^example\.ru$RewriteRule ^(.*)$ https://example.ru/$1 [R=301,L]

Вариант 3 (перенаправление с http://example.ru на https://example.ru с отключением перенаправления для robots.txt).

RewriteEngine OnRewriteBase /RewriteCond % !1RewriteCond % !robots.txtRewriteRule ^(.*)$ https://example.ru/$1 [R=301,L]

Вариант 4 (перенаправление с http://example.ru на https://www.example.ru).

RewriteEngine OnRewriteBase /RewriteCond % !1RewriteCond % ^example\.ru$RewriteRule ^(.*)$ https://www.example.ru/$1 [R=301,L]

Вариант 5 (перенаправление с http://www.forum.example.ru на https://forum.example.ru).

Options +FollowSymLinksRewriteEngine OnRewriteCond % ^www\.forum\.example\.ru$ [NC]RewriteRule ^(.*)$ https://forum.example.ru/$1 [R=301,L]RewriteBase /RewriteCond % !1RewriteRule ^(.*)$ https://%/$1 [R=301,L]

Вариант 6 (перенаправление с http://forum.example.ru на https://www.forum.example.ru).

Options +FollowSymLinksRewriteEngine OnRewriteCond % ^forum\.example\.ru$ [NC]RewriteRule ^(.*)$ https://www.forum.example.ru/$1 [R=301,L]RewriteBase /RewriteCond % !1RewriteRule ^(.*)$ https://%/$1 [R=301,L]

RewriteEngine OnRewriteBase /RewriteCond %1[NC]RewriteCond % ^/Необходимая директория_страница$RewriteRule ^(.*)$ http://%/$1 [R=301,L]

Вариант 2 (общее перенаправление на https, с перенаправлением одной страницы на http). Этот способ часто необходим для CMS Bitrix и корректной работы обмена данными с 1С, т.к. 1C не может подключаться по протоколу https.

RewriteEngine OnRewriteBase /RewriteCond % !1RewriteCond % !^/Необходимая директория_страница$RewriteRule ^(.*)$ https://%/$1 [R=301,L]RewriteCond %1[NC]RewriteCond % ^/Необходимая директория_страница$RewriteRule ^(.*)$ http://%/$1 [R=301,L]

Отключение перенаправления на https для страницы bitrix/admin/1c_exchange.php для корректной работы обмена данных с 1C:

Источник

How to Redirect Website from HTTP to HTTPS?

https

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Go HTTPS; it doesn’t cost anything, and yet you get search engine ranking and security.

HTTPS should be everywhere, and lately, Google has considered this as a ranking signal to their search engine results.

There are two primary reasons you should consider securing your website with an SSL certificate.

  • Security – to ensure sensitive data is encrypted from a user browser to the web server or network edge. Having SSL also give some trust to the visitor that your website is secure.
  • SEO – HTTPS is a new ranking signal, and the big boss is watching you, so don’t be behind in the race.

If you are worried about the cost, then let me remind you, you can get the SSL certificate in FREE from many issuers. And most of the shared hosting offers free SSL.

There are many ways to put this redirection, and the following is the easiest one I find.

Apache

  • Login to your Apache server and go to the path where it’s installed.
  • Go to the conf folder and take a backup of httpd.conf file
  • Open httpd.conf using your vi editor (choose your favorite editor)
  • Ensure mod_rewrite.so module is loaded
LoadModule rewrite_module modules/mod_rewrite.so
  • If you see above line is commented then uncomment it
  • Add the following at the end of the file
RewriteEngine On RewriteCond % off RewriteRule (.*) https://%%

A configured website should be able to redirect and accessible on https.

Nginx

Login to the Nginx web server and take a backup of nginx.conf or default.conf file (whatever file you are using for server directive)

return 301 https://$server_name$request_uri;

Restart Nginx to test the site.

Cloudflare

If you are leveraging Cloudflare for performance and security, then having a website through HTTPS is very easy.

cloudflare-https

There is another way, page rules.

  • Go to Page Rules
  • Click “Create Page Rule”
  • Enter the URL (put the asterisk, so redirection happens for all the URI)
  • Click “Add a Setting” and select “Always Use HTTPS” from the drop-down

cloudflare-pagerules

It will take a few seconds, and you are all set to have your website accessible through https. After using Cloudflare, if your site breaks due to mixed content, then check out the following guide.

cPanel

I assume you are using this on a shared hosting platform. First, you need to ensure the hosting provider offer SSL and enabled for your site.

  • Login to cPanel and go to the files manager where you can find .htaccess file
  • Add the following at the end of the file
RewriteEngine On RewriteCond % off RewriteRule (.*) https://%%

Note: if you already see “RewriteEngine On” in your existing file, then you don’t need to duplicate it.

SUCURI

SUCURI offers FREE cert under the WAF plan, and you can enable it by navigating to the HTTPS/SSL tab.

First, select “Full HTTPS” in SSL mode.

sucuri-ssl-mode

Second, select “HTTPS only site” in protocol redirection.

sucuri-protocol-redirection

Save the configuration, and in a few seconds, you will have your site accessible through https.

Kinsta

Kinsta, a premium WP managed hosting offer Let’s Encrypt certificate and let you force HTTPS with a single click.

  • Login to MyKinsta
  • Select the site you want to enable and enforce HTTPS
  • Go to Tools and enable Force HTTPS

kinsta-https-redirect

SiteGround

SiteGround has its own control panel (earlier cPanel) and lets you implement SSL cert for FREE and give you an option to force every request to HTTPs.

  • Login to SiteGround
  • Go to Websites tab
  • Select Site Tools next to the website

siteground-site-tools

siteground-https-enforce

What’s next?

Once you setup the redirection, ensure all the resources are getting loaded over HTTPS. You can use the Mixed Content Testing tool to verify if any resource is still getting loaded over HTTP.

geekflare-mixed-content-test

If you notice and using WordPress, then you may have to use SSL Insecure Content Fixer Plugin, which will ensure all resources are served over https://.

I hope the above instructions help you. You may also want to test your site to ensure no vulnerabilities in the TLS configuration/certificate.

Источник

Оцените статью