- HTML redirection
- HTML meta refresh redirect
- HTML meta refresh redirect example
- HTML canonical link tag redirect
- See also
- Метатэг Refresh — обновление страницы и перенаправление
- 5 последних уроков рубрики «HTML и DHTML»
- Лайфхак: наиполезнейшая функция var_export()
- 17 бесплатных шаблонов админок
- 30 сайтов для скачки бесплатных шаблонов почтовых писем
- Как осуществить задержку при нажатии клавиши с помощью jQuery?
- Прагма директива refresh
- Примечание
- Поддержка браузерами
- Спецификация
- Значения атрибута «content»
- Auto refresh web page meta tag code example
- Using Javascript to override or disable meta refresh tag
- Auto Refresh the page with Meta Tag
- Meta Refresh
- Comments
HTML redirection
HTML meta refresh redirect is a client side redirect and is not 301 permanent redirect.
The HTML meta refresh with 0 seconds time interval, is considered by Google as a hint for 301 redirect for pagerank transfer.
If you want to do real 301 permanent redirect, you can do it with PHP redirect after enabling PHP code in HTML files.
HTML meta refresh redirect
The redirection is done with the meta refresh in the head section.
The link in the body section for fallback purposes.
Replace old page with redirection code with the URL of the page you want to redirect to.
HTML meta refresh redirect example
Press this link to redirect from html-redirect-test.htm back to this page:
HTML canonical link tag redirect
The canonical link does not redirect to the preferred URL, but it can be an alternative to URL redirection for websites that most of the traffic arrives from search engines.
HTML canonical link tag can be used when there are several pages with similar content and you want to tell the search engines which page you prefer to use in the search results.
Canonical link tag can link to the same domain and also cross-domain.
Add the canonical link tag to the old page to link to the new page.
Add the canonical link tag to the pages that you prefer not to get search engines traffic to link to the preferred page.
The canonical link tag should be added in the section.
See also
Метатэг Refresh — обновление страницы и перенаправление
Если у Вас возникла ситуация, когда страницу сайта нужно периодически обновлять или просто перенаправить посетителя на другую страницу через определенный промежуток времени, то решением здесь может послужить использование специального метатэга «Refresh».
Вот пример для простой перезагрузки страницы, через определенный интервал времени:
где 10 — интервал обновления страницы в секундах.
Вот пример для перевода посетителя на другую страницу (сайт), через определенное время:
где после URL указывается страница (сайт), куда нужно перенаправить посетителя.
Этот прием может пригодиться Вам при использовании формы обратной связи. Когда человек заполнил форму, нажал кнопку «отправить» и его перебрасывает на обработчик, здесь можно поблагодарить человека и поставить метатэг «Refresh» для автоматического перенаправления человека на главную страницу сайта.
Кстати, урок по созданию формы обратной связи для сайта, Вы можете найти здесь: форма обратной связи.
Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: www.ruseller.com
Автор: Евгений Попов
Урок создан: 11 Мая 2008
Просмотров: 126787
Правила перепечатки
5 последних уроков рубрики «HTML и DHTML»
Лайфхак: наиполезнейшая функция var_export()
При написании или отладки PHP скриптов мы частенько пользуемся функциями var_dump() и print_r() для вывода предварительных данных массив и объектов. В этом посте я бы хотел рассказать вам о функции var_export(), которая может преобразовать массив в формат, пригодный для PHP кода.
17 бесплатных шаблонов админок
30 сайтов для скачки бесплатных шаблонов почтовых писем
Создание шаблона для письма не такое уж простое дело. Предлагаем вам подборку из 30 сайтов, где можно бесплатно скачать подобные шаблоны на любой вкус.
Как осуществить задержку при нажатии клавиши с помощью jQuery?
К примеру у вас есть поле поиска, которое обрабатывается при каждом нажатии клавиши клавиатуры. Если кто-то захочет написать слово Windows, AJAX запрос будет отправлен по следующим фрагментам: W, Wi, Win, Wind, Windo, Window, Windows. Проблема?.
Прагма директива refresh
Прагма директива refresh (от англ. «refresh» ‒ «обновить») устанавливает время редиректа и, при необходимости, URL-адрес страницы редиректа. Под временем редиректа подразумевается время по истечении которого произойдёт переадресация страницы. Под URL-адресом страницы редиректа подразумевается адрес страницы на которую произойдёт переадресация текущей страницы.
Примечание
Если страница редиректа не указана, то происходит автоматическое обновление текущей страницы через указанный промежуток времени. Такая особенность важна для ресурсов с быстро изменяющейся информацией (например, новостные ресурсы, ресурсы прогноза погоды, ресурсы курсов валют и прочие).
Поддержка браузерами
Спецификация
Верс. | Раздел | |
---|---|---|
HTML | ||
2.0 | Associated Meta-information: META | Перевод |
3.2 | META | |
4.01 | The META element http-equiv = name [CI]. DTD: Transitional Strict Frameset | |
5.0 | 4.2.5.3 Pragma directives http-equiv=»refresh». | |
5.1 | 4.2.5.3. Pragma directives http-equiv=»refresh». | |
XHTML | ||
1.0 | Extensible HyperText Markup Language DTD: Transitional Strict Frameset | |
1.1 | Extensible HyperText Markup Language |
Значения атрибута «content»
Атрибут « content » должен иметь значение, являющееся строкой из регистронезависимых ASCII символов, которая состоит из следующих составляющих:
<число>Указывает количество секунд до редиректа страницы. В качестве значения количества секунд указывается целое положительное число. Отсчёт времени до редиректа начинается с момента полной загрузки страницы.число>
Отделяет числовое значение от URL-адреса редиректа. В качестве разделителя указывается символ « ; » ТОЧКА С ЗАПЯТОЙ [U+003B] либо символ « , » ЗАПЯТАЯ [U+002C].
, URL=example.html"> ; URL=example.html">
<пробелы>ПРОБЕЛЫ [U+0020] отделяют символы друг от друга для лучшего визуального восприятия. Кавычки, окружающие URL-адрес страницы редиректа, для лучшего визуального восприятия. В качестве кавычки может указываться символ « ‘ » АПОСТРОФ [U+0027] или символ « » » ДВОЙНАЯ КАВЫЧКА [U+0022].пробелы>
Условие использования: кавычки, окружающие URL-адрес страницы, не должны совпадать с кавычками, обозначающими значение « content » атрибута.
Примечание: URL-адреса некоторых ресурсов указываются с учётом регистра символов.
Условие использования: при указании URL-адреса, обязательно указывается « ».
Регистр символов: не учитывается.
Auto refresh web page meta tag code example
Using Javascript to override or disable meta refresh tag
I’ve found that the noscript tag works quite nicely for this. For example, you can place this just after you close the head element:
No need to remove the meta tag with script, since a browser that has script support will ignore everything inside the noscript element.
You cannot override meta refresh tag with JavaScript.
http://example.net/mike.html Put the following code there->
Unfortunately, from @bluesmoon’s answer, manipulating the DOM does not work anymore.
The workaround is to retrieve the original markup, find and replace the meta refresh element, and then write the new document with the replaced markup.
I am not sure how to retrieve the original markup using JavaScript except for sending an additional request using XMLHttpRequest .
In Opera, here is what I am using:
Disable meta refresh 1.00.js :
// ==UserScript== // @name Disable meta refresh // @version 1.00 // @description Disables meta refresh. // @namespace https://stackoverflow.com/questions/3252743/using-javascript-to-override-or-disable-meta-refresh-tag/13656851#13656851 // @copyright 2012 // @author XP1 // @homepage https://github.com/XP1/ // @license Apache License, Version 2.0; http://www.apache.org/licenses/LICENSE-2.0 // @include http*://example.com/* // @include http*://*.example.com/* // ==/UserScript== /* * Copyright 2012 XP1 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser: true, vars: true, maxerr: 50, indent: 4 */ (function (window, XMLHttpRequest) < "use strict"; if (window.self !== window.top) < return; >window.stop(); var uri = window.location.href; var request = new XMLHttpRequest(); request.open("GET", uri, false); request.send(null); if (!(request.readyState === 4 && request.status === 200)) < return; >var markup = request.responseText; markup = markup.replace(//gi, ""); var document = window.document; document.open(); document.write(markup); document.close(); >(this, this.XMLHttpRequest));
Opera also has a built-in feature that disables meta refreshes. No need for JavaScript.
- Right click on webpage > Edit Site Preferences. > Network > Disable «Enable automatic redirection» > OK.
HTML meta http-equiv Attribute, HTML tag Example Refresh document every 30 seconds: Try it Yourself » Definition and Usage The http-equiv attribute provides an HTTP header for the information/value of the content attribute. The http-equiv attribute can be used to simulate an HTTP …
Auto Refresh the page with Meta Tag
Hi, I have a page which has the tag, < meta http-equiv ="refresh" content ="120"/>this page will refresh automatically. This page consists of some controls like drop down list etc. While the page refreshed (automatically) I want the user selection to be maintained. For this what are the ways we can do it and can anyone tell which is the best method to solve this issue. Thank you.
From your description, I understand that there is web form page which contains a dropdownlist
control, and the page would auto-refresh every 120 seconds. The issue you want to resolve is
how to keep the selected value of the Dropdownlist control.
Please feel free to correct me if I have misunderstood your concern.
I have written a sample to demonstrate how you can do that. Please check the code snippet below.
Hope this Information is helpful!
Meta Refresh
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
This will only work if it is enabled in the browser settings. I belief it’s enabled by default but don’t depend on it. To be sure, always use a “Click here if it does not redirect in 5 seconds”-link.
Very easy. If you use Internet Explorer. I always use Firefox. But you’ve got to keep in mind that it is possible to disable meta refreshes. That’s why most sites have the “Click here to continue” or “Click here if it does not forward” links. En by the way, even while I’m using Firefox, I prefer those links. Most of the times it’s faster to click that link than to wait for their timer to finish and forward.
Ok, but I think nobody will disable meta tags manually in their browser settings if they do not have special reason for it. In some cases you can not use url redirect(“click here”) or server side code, so this one comes useful.
bro i just like to say that u r smart as its true most of us will disable meta tags manually in their browser settings if they do not have special reason for it.
I agree with ur point… Hats off… Bravo…
WHY WOULD YOU SAY SUCH THINGS ON THE INTERNET.
Obviously header(“refresh:5;url=YOUR URL”); is a ridiculous and idiotic use of a php function. You can not create asynchronous delayed refreshes in PHP. The header function provides a header which has to be received by the client in the header part of your request. Also the syntax you provided is completely wrong and why would you even assume that html meta tags and php/http headers share a common layout?
Seriously.
Do NOT listen to this guy. Either he’s a troll or he really is the dumbest person alive.
It would be better for everybody if his entries got removed.
I know this is super old, but I was amused how angry John D. evidently was about it. The ‘refresh’ header does in fact work just as described by Kostas, with exactly that syntax, and that indeed is how you set it in PHP using header(). It’s entirely non-standard I think but it is (or at least was) supported by some browsers. I’m not sure how many still support it today. I think Netscape invented it but I don’t think it’s part of any W3C or IETF spec. A few older applications still set a ‘refresh’ header. The right approach to use for redirection is of course just to use a redirect header. Browsers don’t generally expose the functionality to turn off meta refreshing, but if you need to use it for some reason (e.g. because you can’t set headers), provide a link that takes the user to the same page too.
Header(‘location: Ur URL’) ;
Header(“refresh:10; url= ‘ ur URL’ “) ; Why header didn’t work if there is output before
I recommend the triple solution complex! i.e Javascript redirect, meta tag refresh and link to the destination page. I have a page that a counter should count for 60 seconds then javascript should redirect, some times the client claims that redirect failed, so I added meta tag to refresh at 62 seconds and a hidden link that javascript show it after 60 seconds.