Redirect html page to another html page

Разбираем все виды редиректов (html, js, php, htaccess)

Примеры редиректов или же перенаправлений на другую страницу.

Редирект в HTML

// Обновить страницу через 5 секунд: // Перенаправить на https://www.google.com через 5 секунд: // Перенаправьте на https://www.google.com немедленно: 

Редирект в JavaScript

Метод replace() позволяет заменить одну страницу другой таким образом, что это замещение не будет отражено в истории просмотра HTML-страниц (history) браузера

location.replace("https://www.google.com"); document.location.replace("https://www.google.com");

Метод reload() полностью моделирует поведение браузера при нажатии на кнопку reload в панели инструментов. Если вызывать метод без аргумента или указать его равным true , то браузер проверит время последней модификации документа и загрузит его либо из кеша (если документ не был модифицирован), либо с сервера. Такое поведение соответствует нажатию на кнопку reload . Если в качестве аргумента указать false , то браузер перезагрузит текущий документ с сервера. Такое поведение соответствует одновременному нажатию на reload и кнопки клавиатуры shift (reload+shift) .

window.location.reload("https://www.google.com");

Следующие примеры тоже перенаправят на google:

location="https://www.google.com"; document.location.href="https://www.google.com";

С помощью функции setTimeout возможно реализовать задержку переадресации перед выполнением редиректа (в примере — 5 секунд):

setTimeout( 'location="https://www.google.com";', 5000 );

Простой пример редиректа с таймером:

Редирект в PHP

В php есть функция header() , которая разрешает не только подменять стандартные заголовки, но и добавлять новые.

// string - полностью сформированная строка заголовка, который необходимо добавить (без завершающего перевода строки "\n") // replace указывает, нужно ли заменять заголовки с одинаковыми именами (true), или же добавлять в конец (false) // http_response_code указывает код http-ответа (300, 301, 302 и т.д.) void header ( string string [, bool replace = true [, int http_response_code]] );
header( 'Refresh: 0; url=/error404.html' ); // переадресовать на страницу ошибки немедленно (без задержки) header( 'Refresh: 5; url=https://www.google.com/' ); // переадресовать на главную страницу Рамблера через 5 секунд после загрузки страницы. header( 'Location: /', true, 307 ); // перебросить на главную страницу сайта с использованием 307 редиректа. header( 'Location: /article/page.htm', true, 303 ); // с помощью 303 редиректа переадресовать на внутреннюю страницу сайта. header( 'Location: http://google.ru/search?q=redirect' ); // с помощью 302 редиректа переадресовывать на поиск в гугле слова redirect (При использовании Location без указания кода редиректа, по умолчанию используется 302-й). header( 'Location: http://yandex.ru/yandsearch?text=redirect', true, 301 ); // сделать переадресацию с помощью 301 редиректа на поиск в Яндексе слова redirect.

Второй вариант, аналогичный по смыслу, но может быть полезным, если установка кода и редирект должны осуществляться в разных местах:

header('HTTP/1.1 301 Moved Permanently'); header('Location: http://site.com/');

Первая строка указывает код http, а вторая, собственно, задает адрес. В большинстве случаев, проблем не возникнет. Однако, если у вас используется режим FastCGI , то вместо «HTTP/1.1 301 Moved Permanently» может потребоваться написать «Status: 301 Moved Permanently» .

Редирект в .htaccess (RewriteEngine)

Redirect [status] URL-path URL-to-redirect

Необязательный параметр status — это три цифры — код редиректа (например, 301). Если не указан, то по умолчанию подставляется 302.

Читайте также:  Python dataframe row number

URL-path — часть запрашиваемого пользователем (или поисковиком) адреса, которая должна обязательно начинаться со слеша (/)

URL-to-redirect — полный адрес сайта (и, возможно, часть пути), на который будет осуществляться редирект. Должен быть вида http://site.ru/ — то есть обязательно должен присутствовать протокол (http://) и закрывающий адрес сайта слеш (/).

Если URL-path заканчивается не слешем, то редирект будет срабатывать только в случае точного совпадения запрошенного пользователем адреса и URL-path .

Если URL-path заканчивается слешем, то редирект сработает не только для указанного адреса, но и для всех, которые начинаются на указанный. А к URL-to-redirect будет добавлена часть адреса, следующая за последним указанным слешем в URL-path .

Действие директивы RedirectMatch аналогично Redirect , но в параметрах URL-regexp и URL-to-redirect можно использовать регулярные выражения.

// должно быть включено (on) для работы RewriteRule RewriteEngine on RewriteRule URL-regexp URL-to-redirect [L,R[=status]]

У директивы RewriteRule более широкий спектр применения. Который, в числе прочих возможностей, разрешает ее использования и для редиректа — с указанием в конце строки в квадратных скобках [ ] флагов L (выполнить немедленно) и R (редирект).

Redirect / http://yandex.ru/yandsearch?text= # Выполнится 302 редирект (по умолчанию) на поиск в Яндексе символов, введенных в адресную строку после названия Вашего сайта. # То есть если посетитель введет http://ваш_сайт.ru/page, то браузер его перенаправит на http://yandex.ru/yandsearch?text=page Redirect 301 /hello.html http://google.ru/search?q=bye # В случае перехода на страницу http://ваш_сайт.ru/hello.html выполнится 301 редирект на поиск в Гугле фразы "bye". RedirectMatch (.*)\.jpg$ http://хостинг_для_картинок$1.jpg # "Временно" (по умолчанию действует 302 редирект) переадресовываем все запросы jpeg-картинок на какой-либо бесплатный хостинг # или то же самое, но с применением RewriteRule: RewriteEngine on RewriteRule (.*)\.jpg$ http://хостинг_для_картинок$1.jpg [L,R]

Редирект в Yii2

$this->registerMetaTag(['http-equiv' =>'Refresh', 'content' => '5; http://google.ru/']);

Источник

How to Easily Make HTML Redirect to Another Page

TL;DR – HTML redirect takes a website visitor to another site automatically.

Contents

What is an HTML Redirect?

A redirect happens when a user enters a URL, but it changes, and the browser takes them to a different one instead. Website creators rely on them when they need to change the structure of their site or the location of a particular page. Of course, you may redirect to a completely different website as well.

When working with Hypertext Transfer Protocol (HTTP), you need to have a basic understanding of its response codes. They contain three digits, first of which defines their type:

Let’s say you closed your old website and opened a new one. If a user types a URL of the old one into their browser, it will return the response code 404 (Not Found). However, if you use an HTML redirect, the user will get either 301 (Moved Permanently) or 302 (Found). This code is invisible to the user, but the browser understands it and redirects the user to the new URL in moments.

Читайте также:  Принципы работы сборщика мусора java

The Syntax for HTML Redirect Code

The HTML redirect is also known as the meta refresh redirect, or simply HTML meta redirect. It allows you to choose whether you need an immediate or a delayed redirect. If you specify the delay time in seconds, the user will see the old page for exactly that long.

To make a page in HTML redirect to another page, you should follow this syntax:

meta http-equiv="refresh" content="time; URL=new_url" />

As you can see, it requires two parameters:

  • time represents the delay before the browser redirects the user to a different page. Define it in seconds, or enter a 0 if you need an immediate HTML redirect.
  • new_url represents the URL address you need to redirect your user to after the delay.

In the example below, you can see the HTML redirect code that takes the user to BitDegree’s website with a delay of five seconds:

meta http-equiv="refresh" content="5; URL=https://www.bitdegree.org/" />
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion

Why Delay a Redirect in HTML?

If you’re not sure why you should delay your HTML meta redirect, think about a chance to set a message for the user. You could inform them the page has moved, and then promptly send them to the new one.

Another important reason is the slight chance of the tag not being rendered correctly. This might happen if the user is using some ancient browser. In this case, you may add a direct link to the old page which the user might click manually if the HTML redirect code fails.

head> meta http-equiv="refresh" content="5; URL=https://www.bitdegree.org/" /> head> body> p>If you are not redirected in five seconds, a href="https://www.bitdegree.org/">click here a>. p> body>

As you can see, all you need to add a direct clickable link is a pair of anchor tags. Make sure to place it in the section and not the with the HTML meta redirect tag: there is no use for a clickable link that a user cannot see in the first place.

HTML Redirect: Useful Tips

  • If you don’t define a new URL address for the redirect, HTML page will simply reload itself after the time specified. It can be useful when you need to refresh dynamic content.
  • We’d advise you to avoid delays shorter than 3 seconds, as that makes it virtually impossible for the user to click the Back button on their browser.
  • Be careful not to overuse HTML meta redirects: if your website has a ton of them, the search engines may think it contains spam and remove it from their index.
  • You can also create redirects with PHP, JavaScript, Ruby on Rails, and Python Flask, as well as in the Apache, Nginx, and Lighttpd web servers.
Читайте также:  Re match python flags

Источник

How to Redirect a Web Page in HTML

To tell search engines and website visitors that your web page has permanently moved to a new location with an equivalent content use a 301 redirect. The code “301” is interpreted as “moved permanently”. (Learn more about HTTP Status Codes).

How to redirect to another URL

content="0; url='https://www.w3docs.com'" />

If you want your redirection to occur in an exact time, just specify your preferred parameter (in seconds) for the content . Let’s consider an example, where we set «7» seconds as redirection time.

Some browsers don’t render the refresh tag correctly, so before the next page loads, the user can see a flash as a page.

content="7; url='https://www.w3docs.com'" />

Some old browsers don’t refresh correctly when you add a quick link. In that case, you can add an anchor link to let the user follow.

Example of redirecting a web page:

html> html> head> meta http-equiv="refresh" content="7; url='https://www.w3docs.com'" /> head> body> p>You will be redirected to w3docs.com soon! p> body> html>

How to redirect to a new page without leaving the current page:

If you want to redirect to another website without leaving the current website and open a link that redirects to an HTML document, you can use the anchor tag with the «target» attribute set to «_blank». This will open the link in a new window or tab, while the current website remains open.

Here’s an example of how to use it:

html> html> head> title>Redirecting without leaving the current page title> head> body> a href="https://www.w3docs.com" target="_blank">Click here to go to W3docs.com a> body> html>

In this example, clicking on the link will open «https://www.w3docs.com» in a new window or tab, while the current website remains open.

If you want to redirect to an HTML document instead of a website, you can use the same method by setting the link’s href attribute to the path of the HTML document you want to redirect to.

In this example, clicking on the link will open «example.html» in a new window or tab while the current website remains open.

Learn more about redirecting web pages with JavaScript, PHP, Apache and Node.js.

Источник

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