Php redirect 301 302

PHP: Редирект 301 и 302

Редиректы или перенаправления в PHP это просто. Мы рассмотрим их шаг за шагом и я покажу, как избежать некоторых ловушек. Мы узнаем нюансы между 301 и 302 перенаправлением.

Для перенаправления на другую страницу с кодом 302 используйте функцию PHP header() .

header('Location: https://example.com/path/to/page');

Довольно просто, верно? Однако есть нюансы о которых следует помнить.

Не выводите текст перед отправкой заголовков

Следующий PHP код вызовет предупреждение:

 

echo 'Hello, World!';

header('Location: https://example.com/some/page');
Warning: Cannot modify header information - headers already sent by

Остановите выполнение кода

В большинстве случаев после отправки заголовка header() вам нужно будет остановить выполнение кода с помощью PHP функции exit() :

 

if (! empty($_POST['redirect']))
header('Location: https://example.com/some/page');

exit;
>

// После отправки заголовка выполнение кода будет остановлено благодаря exit()

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

Устанавливайте корректный HTTP код

Функция header() может принимать параметры. Например, когда вы добавляете заголовок Location , будет автоматически установлен HTTP код 302 . Но если мы хотим выполнить перенаправление на новый URL с кодом 301 ?

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

Часто задаваемые вопросы

Это должен быть редирект 302 или редирект 301?

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

Редирект 302 постоянный?

Редирект 302 временный — не постоянный.

Для чего используется редирект 302?

HTTP код 302 означает, что запрошенная страница была временна перемещена по другому адресу, указанному в поле Location заголовка страницы.

Редирект 302 использует в следующих случаях:

  • Вы продвигаете новый продукт, и хотите временно перенаправлять на него своих посетителей в течении ограниченного периода времени. Сохраняя при этом рейтинг своей страницы в поисковых системах и/или её позицию в поисковой выдаче.
  • Товар распродан и вам нужно временно переправить пользователей на страницу с другим товаром.
  • A/B тестирование. Вы хотите временно перенаправлять посетителей на другую страницу не влияя на поисковый рейтинг текущей станицы.

Однако следует заметить, что редирект 302 используется если метод запроса был GET или HEAD или вам неважно содержимое и заголовок запроса. В иных случаях следует использовать редирект 307 (например для запроса PUT ), заголовок и содержимое будут в не изменённом виде переданы по новому адресу указанному в поле Location .

Если требуется изменить метод запроса на GET — используйте редирект 303. Это бывает полезно если был запрос с методом PUT и вы хотите подтвердить выполненное действие.

Для чего используется редирект 301?

HTTP код 301 означает, что запрошенная страница была окончательно перенесена на новый адрес указанный в поле Location заголовка страницы.

Некоторые варианты использования редиректа 301:

  • Принудительное перенаправление с HTTP на HTTPS.
  • Перенаправление со старых URL-адресов на новые (если мы не хотим, чтобы люди натыкались на мёртвые ссылки). Полезно при переходе на новый домен.

Что лучше редирект 302 или 301?

Ни один из них не лучше или хуже другого. Используйте тот, который подходит в вашей ситуации. Эта статья должна помочь разобраться.

Источник

PHP redirect: 301 and 302

Hundreds of developers subscribed to my newsletter.
Join them and enjoy free content about the art of crafting web applications!

To perform a 302 redirect in PHP, use the header() function to set the new location.

 
header('Location: https://example.com/path/to/page');

Easy, right? There’s one thing to remember going forward, though.

  • Don’t output text before sending headers
  • Stop code execution
  • Set the correct HTTP code
  • Frequently Asked Questions
  • Should a redirect be 301 or 302?
  • Is 302 a permanent redirect?
  • What are 302 redirects used for?
  • What are 301 redirects used for?
  • Which is better, a 301 or 302 redirect?

PHP redirect: 301 and 302

Don’t output text before sending headers

 
echo 'Hello, World!';
header('Location: https://example.com/some/page');

This will result in a warning:

 
Warning: Cannot modify header information - headers already sent by

Stop code execution

Most of the time, you will need to stop code execution with the exit() function. Here’s an example:

 
if (! empty($_POST['redirect']))
header('Location: https://example.com/some/page');
exit;
>
// The following code will never be executed thanks to exit().

If you don’t stop code execution, the user will be redirected to the new URL after the code has finished running.

Set the correct HTTP code

The header() function can take a third parameter.

For instance, when you add a Location header, the HTTP code will automatically be set to 302 .

But what if we want to perform a 301 redirect to the new URL instead?

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

Frequently Asked Questions

Should a redirect be 301 or 302?

Most of the time, you should stick to the default 302 redirect, unless you want to permanently redirect your users.

Is 302 a permanent redirect?

302 redirects are not permanent.

What are 302 redirects used for?

302 redirects are used for the following scenarii:

  • You have a promotion for a product and you want to redirect your visitors to it for a limited time, while preserving the ranking of your page on search engines results pages (or SERPs, for SEO nerds out there);
  • A product is sold out, we need to redirect users to a new one for a limited time;
  • A/B testing. You want to redirect some visitors to a another page, still without affecting your ranking.

What are 301 redirects used for?

The HTTP 301 code means the resource has been moved permanently.

  • Redirect from HTTP to HTTPS;
  • Redirect from www to non-www URLs;
  • Redirect old URLs to new ones (we don’t want people to stumble upon dead links). This is useful when migrating to a new domain.

Which is better, a 301 or 302 redirect?

None is better than the other. Use whichever is the most appropriate to your needs. This article should help you figure it out.

Article written by Benjamin Crozat

I built Smousss, an AI-powered assistant for Laravel developers.

Источник

PHP Redirects – How to Create and Configure them

PHP Redirects – How to Create and Configure them

PHP redirect is a method used to redirect a user from one page to another page without clicking any hyperlinks.

This will be helpful in such circumstances when you want to redirect a certain page to a new location, change the URL structure of a site and redirect users to another website.

Redirection is very important and frequently used in Web Development phases.

There are several reasons to use PHP redirect, including, Merger of two websites, Change of business name, Redirect traffic to updated content and many more.

In this tutorial, we will learn how to redirect PHP page with the header() function.

PHP Redirect Basic Syntax

To use a redirect in PHP, we use a header() function. The header() function is an inbuilt function in PHP which is used to send a raw HTTP header to the client.

Basic syntax of header() function in PHP redirect is shown below:

header( header, replace, http_response_code )

Each parameter is described below:

  • header:
    This is used to hold the header string to send
  • replace:
    Indicates the header should replace a previous similar header, or add a second header of the same type
  • http_response_code:
    This is used to hold the HTTP response code

PHP Redirect Example

In this section, we will give you a quick example of how to create a redirect using PHP.

In this example, we will create a page1.php that contains code that issues a redirect and page2.php that contains just HTML.

Add the following contents:

Save and close the file. Then, create a page2.php:

Add the following contents:


This my page2


Save and close the file, when you are finished.

Next, you can test the URL redirection by visiting the page1.php at URL http://localhost/page1.php. You will be redirected to the page2.php as shown below:

php-redirect

You can also test the URL redirection with Curl command:

curl -I http://localhost/page1.php

You should see the following output:

HTTP/1.1 302 Moved Temporarily
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 11 Sep 2019 09:48:42 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.29
Location: page2.php

By default, search engine replies with the default response code 302 while Browser reply with the response code 30x.

If you want to redirect page1.php to another site https://www.webservertalk.com with response code 301 then edit the php1.php file with the following contents:

Add the following contents:

header(«Location: https://www.webservertalk.com»,TRUE,301);
exit;
?>

Save and close the file. Then, check PHP redirect again with the Curl command:

curl -I http://localhost/page1.php

You should see the following output:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 11 Sep 2019 10:21:58 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.29
Location: https://www.webservertalk.com

PHP Redirect with Absolute URL

In the above examples, The URL does not contain a hostname, this will work on modern browser. But, it is better to redirect to an absolute URL.

You can achieve this by editing the page1.php file as shown below:

Make the following chages:

header(‘Location: http://’ . $_SERVER[‘HTTP_HOST’] . ‘/page2.php’);
exit;
?>

Save and close the file when you are finished. Then, you can test it with your web browser or Curl command.

PHP Redirect with Time Delay

You can also redirect PHP page to another page with refresh function instead of Location.

For example, create a page1.php that redirect to page2.php after 10 seconds:

Add the following contents:

header( «refresh:10; url=/page2.php» );
echo «Redirecting in 10 secs.»;
exit;
?>

Save and close the file. Then, check the URL redirection by visiting the URL http://localhost/page1.php. You should see the following page:

Above page indicates that page1.php will redirects after 10 seconds.

Conclusion

In the above tutorial, we have learned how to redirect URL from one page to another with PHP header() function.

I hope you have now enough knowledge on how PHP redirection works. For more information, you can visit the PHP redirect documentation at PHP redirect.

Recent Posts

  • Forcepoint Next-Gen Firewall Review & Alternatives
  • 7 Best JMX Monitoring Tools
  • Best PostgreSQL Backup Tools
  • Best CSPM Tools
  • Best Cloud Workload Security Platforms
  • Best Automated Browser Testing Tools
  • Event Log Forwarding Guide
  • Best LogMeIn Alternatives
  • Citrix ShareFile Alternatives
  • SQL Server Security Basics
  • Cloud Security Posture Management Guide
  • Cloud Workload Security Guide
  • The Best JBoss Monitoring Tools
  • ITL Guide And Tools
  • 10 Best Enterprise Password Management Solutions

Источник

Читайте также:  Генерация jwt токена java
Оцените статью