Response redirect html code

Разбираем все виды редиректов (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.

Читайте также:  Javascript work with time

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/']);

Источник

Response: redirect() static method

The redirect() static method of the Response interface returns a Response resulting in a redirect to the specified URL.

Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page’s request and redirect it as desired. This will actually lead to a real redirect if a service worker sends it upstream.

Читайте также:  Hiding an html link href

Syntax

.redirect(url) Response.redirect(url, status) 

Parameters

The URL that the new response is to originate from.

An optional status code for the response (e.g., 302 .)

Return value

Exceptions

The specified status is not a redirect status.

The specified URL is invalid.

Examples

.redirect("https://www.example.com", 302); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 12, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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.

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.
Читайте также:  Javascript ajax response text

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.

Источник

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