Window location replace php

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

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 Make a Redirect in PHP

Redirects are particularly useful when web admins are migrating websites to a different domain, implementing HTTPS, or deprecating pages.

There are several ways to implement a redirect, with PHP redirects being one of the easiest and safest methods. A PHP redirect is a server-side redirect that quickly redirects users from one web page to another.

Even though PHP redirects are considered safe, not implementing them correctly can cause serious server issues.

This guide explains two ways to set up a PHP redirect, and the advantages and disadvantages of each method.

How to set up a PHP redirect.

Method 1: PHP Header Function

The fastest and most common way to redirect one URL to another is by using the PHP header() function.

The general syntax for the header() function is as follows:

header( $header, $replace, $http_response_code ) 
  • $header . The URL or file name of the resource being redirected to. Supported file types include but are not limited to HTML, PDF, PHP, Python, Perl, etc.
  • $replace(optional). Indicates whether the current header should replace a previous one or just add a second header. By default, this is set to true . Using false forces the function to use multiple same-type headers.
  • $http_response_code(optional). Sets the HTTP response code to the specified value. If not specified, the header returns a 302 code.

Important: To correctly redirect using the header() function, it must be placed in the page’s source code before any HTML. Place it at the very top of the page, before the !DOCTYPE declaration.

Consider the following PHP code example:

The defined header() function redirects the page to http://www.example.com/example-url, replaces any previous header function and generates a 301 response code.

The exit() or die() function is mandatory. If not used, the script may cause issues.

Note: Permanent (301) redirects are typically used for broken or removed pages. That way, users are redirected to a page relevant to them.

Method 2: JavaScript via PHP

If using the PHP header() function is not a viable solution, use JavaScript to set up a PHP redirect. Take into consideration that JavaScript redirects via PHP work slower and require the end user’s browser to have JS enabled and downloaded.

There are three ways to set up a PHP redirect using the JS window.location function:

Below is a brief overview of the differences between the three options:

window.location.href window.location.assign window.location.replace
Function Returns and stores the URL of the current page Replaces the current page. Loads a new document.
Usage Fastest JS redirect method. Used when the original webpage needs to be removed from browser history. Safer than href.
Does it show the current page?
Does it add a new entry to the user’s browser history?
Does it delete the original page from the session history?

window.location.href

window.location.href sets the location property of a page to a new URL.

The following code is used to call window.location.href via PHP.

 window.location.href="http://www.example-url.com" ?> 

The advantage of window.location.href is that it is the fastest-performing JS redirect. The disadvantage is that if the user navigates back, they return to the redirected page.

window.location.assign

window.location.assign() calls a function to display the resource located at the specified URL.

Note: window.location.assign() only works via HTTPS. If the function is used for an HTTP domain, the redirect does not function, and it displays a security error message instead.

The following code snippet calls the window.location.assign() via PHP:

 window.location.assign("http://www.example-url.com") ?> 

The disadvantage of using window.location.assign() is that its performance and speed is determined by the browser’s JavaScript engine implementation. However, its the safer option. Should the target link be broken or unsecure, the function will display a DOMException – an error message.

window.location.replace

window.location.replace() replaces the current page with the specified URL.

Note: window.location.replace() only works on secure domains (HTTPS) too.

The following code is used to call window.location.replace() via PHP:

 window.location.replace("http://www.example-url.com") ?> 

Once a page is replaced, the original resource does not exist in the browser’s history anymore, meaning the user cannot click back to view the redirected page.

The advantage of window.location.replace() is that, just like window.location.assign() , it does not allow redirects to broken or unsecure links, in which case it outputs a DOMException .

The disadvantage of window.location.replace() is that it may perform slower than window.location.href() .

PHP Header Vs. JS Methods — What to Use?

The general consensus is that the PHP header() function is the easiest and fastest way to set up a PHP redirect. JavaScript via PHP is typically reserved as an alternative when setting up the PHP header fails.

This is due to two reasons:

  • JavaScript must be enabled and downloaded on the end user’s browser for redirects to function.
  • JavaScript redirects perform slower.

You now know how to set up a PHP redirect using the header() function or through some clever use of JavaScript.

After setting up redirects, monitor their performance. A routine website audit can detect the presence of redirect loops and chains, missing redirects or canonicals, and potential setup errors (redirects being temporary instead of permanent, and vice versa).

Источник

Как сделать редирект PHP

Как сделать редирект PHP

На страницах сайтов постоянно что-то добавляется, удаляется и обновляется, чтобы в поисковиках была только актуальная информация и нужные страницы не выпадали из поиска применяются редиректы. Также редиректы используются после отправки форм чтобы не было возможности отправить форму несколько раз.

  • 301 – текущая страница удалена на всегда, заменой старой считать новый URL.
  • 302 – текущая страница временно не доступна, заменой считать пока новый URL.
  • 303 – используется после отправки формы методом POST (подробнее Post/Redirect/Get — PRG).

Итак, сделать 301-й редирект можно так:

header('Location: https://example.com', true, 301); exit();

Но функция header() не сработает если до ее вызова в браузер уже выводился какой-то контент и вызовет ошибку:

Warning: Cannot modify header information — headers already sent by…

Исправить ее можно использовав буферизацию вывода добавив в самое начало скрипта ob_start() ;

Также можно подстраховаться добавив JS-редирект и ссылку если функция header() не сработает.

Упростить использование кода можно выделив его в отдельную функцию:

function redirect($url, $code = 301) < header('Location: ' . $url, true, $code); echo ""; echo 'Перенаправление… Перейдите по ссылке.'; exit(); > /* В index.php */ if ($_SERVER['REQUEST_URI'] == '/url-old') < redirect('https://example.com/url-new'); >
$urls = array( array('/url-old-1', 'https://example.com/url-new-1'), array('/url-old-2', 'https://example.com/url-new-2'), array('/url-old-3', 'https://example.com/url-new-3'), ); foreach ($urls as $row) < if ($_SERVER['REQUEST_URI'] == $row[0]) < redirect($row[1]); >>

Источник

Читайте также:  Document
Оцените статью