Ошибка 302 moved temporarily

This question was asked a long ago, while the RFC 2616 was still hanging around. Some answers to this question are based in such document, which is no longer relevant nowadays. Quoting Mark Nottingham who, at the time of writing, co-chairs the IETF HTTP and QUIC Working Groups:

Don’t use RFC2616. Delete it from your hard drives, bookmarks, and burn (or responsibly recycle) any copies that are printed out.

The old RFC 2616 has been supplanted by the following documents that, together, define the HTTP/1.1 protocol:

  • RFC 7230: Message Syntax and Routing
  • RFC 7231: Semantics and Content
  • RFC 7232: Conditional Requests
  • RFC 7233: Range Requests
  • RFC 7234: Caching
  • RFC 7235: Authentication

And, as of June 2022, a new set of RFCs obsoleted the documents listed above:

  • RFC 9110: HTTP Semantics
  • RFC 9111: HTTP Caching
  • RFC 9112: HTTP/1.1

So I aim to provide an answer based in the RFC 9110, which is the current reference for the HTTP semantics.

The 302 status code

A response with 302 is a common way of performing URL redirection. Along with the 302 status code, the response should include a Location header with a different URI. Such header will be parsed by the user agent and then perform the redirection:

Redirection example

Web browsers may change from POST to GET in the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

This is how the 302 status code is defined in the RFC 9110:

6.4.3. 302 Found

The 302 (Found) status code indicates that the target resource
resides temporarily under a different URI. Since the redirection
might be altered on occasion, the client ought to continue to use the
target URI for future requests.

The server SHOULD generate a Location header field in the response
containing a URI reference for the different URI. The user agent MAY
use the Location field value for automatic redirection. The server’s
response content usually contains a short hypertext note with a
hyperlink to the different URI(s).

Note: For historical reasons, a user agent MAY change the
request method from POST to GET for the subsequent request. If
this behavior is undesired, the 307 (Temporary Redirect) status
code can be used instead.

According to MDN web docs from Mozilla, a typical use case for [302]302] is:

The Web page is temporarily not available for reasons that have not been unforeseen. That way, search engines don’t update their links.

Other status codes for redirection

The RFC 9110 defines the following status codes for redirection (some of these status codes were originally defined in other RFCs, but have all been consolidated in the RFC 9110):

  • 301: Moved Permanently
  • 302: Found
  • 307: Temporary Redirect
  • 308: Permanent Redirect

Refer to this answer for further details.

From Wikipedia, the free encyclopedia

The HTTP response status code 302 Found is a common way of performing URL redirection. The HTTP/1.0 specification (RFC 1945) initially defined this code, and gave it the description phrase «Moved Temporarily» rather than «Found».

An HTTP response with this status code will additionally provide a URL in the header field Location. This is an invitation to the user agent (e.g. a web browser) to make a second, otherwise identical, request to the new URL specified in the location field. The end result is a redirection to the new URL.

Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g. POST).[1] For this reason, HTTP/1.1 (RFC 2616) added the new status codes 303 and 307 to disambiguate between the two behaviours, with 303 mandating the change of request type to GET, and 307 preserving the request type as originally sent. Despite the greater clarity provided by this disambiguation, the 302 code is still employed in web frameworks to preserve compatibility with browsers that do not implement the HTTP/1.1 specification.[2]

As a consequence, RFC 7231 (the update of RFC 2616) changes the definition to allow user agents to rewrite POST to GET.[3]

Example[edit]

Client request:

GET /index.html HTTP/1.1
Host: www.example.com

Server response:

HTTP/1.1 302 Found
Location: http://www.iana.org/domains/example/

See also[edit]

  • List of HTTP status codes
  • HTTP 301

References[edit]

  1. ^ Lawrence, Eric. «HTTP Methods and Redirect Status Codes». EricLaw’s IEInternals blog. Retrieved 2011-08-20.
  2. ^ «Request and response objects | Django documentation | Django». Docs.djangoproject.com. Retrieved 2014-06-23.
  3. ^ «Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content». Tools.ietf.org. Retrieved 2019-01-05.

External links[edit]

  • RFC 7230, RFC 7231, RFC 7232, RFC 7233, RFC 7234, RFC 7235 (HTTP 1.1)
  • RFC 2616 (HTTP 1.1) (obsolete)
  • RFC 1945 (HTTP 1.0)

This question was asked a long ago, while the RFC 2616 was still hanging around. Some answers to this question are based in such document, which is no longer relevant nowadays. Quoting Mark Nottingham who, at the time of writing, co-chairs the IETF HTTP and QUIC Working Groups:

Don’t use RFC2616. Delete it from your hard drives, bookmarks, and burn (or responsibly recycle) any copies that are printed out.

The old RFC 2616 has been supplanted by the following documents that, together, define the HTTP/1.1 protocol:

  • RFC 7230: Message Syntax and Routing
  • RFC 7231: Semantics and Content
  • RFC 7232: Conditional Requests
  • RFC 7233: Range Requests
  • RFC 7234: Caching
  • RFC 7235: Authentication

And, as of June 2022, a new set of RFCs obsoleted the documents listed above:

  • RFC 9110: HTTP Semantics
  • RFC 9111: HTTP Caching
  • RFC 9112: HTTP/1.1

So I aim to provide an answer based in the RFC 9110, which is the current reference for the HTTP semantics.

The 302 status code

A response with 302 is a common way of performing URL redirection. Along with the 302 status code, the response should include a Location header with a different URI. Such header will be parsed by the user agent and then perform the redirection:

Redirection example

Web browsers may change from POST to GET in the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

This is how the 302 status code is defined in the RFC 9110:

6.4.3. 302 Found

The 302 (Found) status code indicates that the target resource
resides temporarily under a different URI. Since the redirection
might be altered on occasion, the client ought to continue to use the
target URI for future requests.

The server SHOULD generate a Location header field in the response
containing a URI reference for the different URI. The user agent MAY
use the Location field value for automatic redirection. The server’s
response content usually contains a short hypertext note with a
hyperlink to the different URI(s).

Note: For historical reasons, a user agent MAY change the
request method from POST to GET for the subsequent request. If
this behavior is undesired, the 307 (Temporary Redirect) status
code can be used instead.

According to MDN web docs from Mozilla, a typical use case for [302]302] is:

The Web page is temporarily not available for reasons that have not been unforeseen. That way, search engines don’t update their links.

Other status codes for redirection

The RFC 9110 defines the following status codes for redirection (some of these status codes were originally defined in other RFCs, but have all been consolidated in the RFC 9110):

  • 301: Moved Permanently
  • 302: Found
  • 307: Temporary Redirect
  • 308: Permanent Redirect

Refer to this answer for further details.

HTTP response status code 302 Found, also previously known as “Moved Temporarily», is returned by the server to indicate that the client redirects to a new location specified within the Location HTTP header, because HTTP response is temporary it is expected to be revalidated upon the next time the URI is requested.

Usage

When the 302 Found status code is received, the client will understand that the requested resource has temporarily moved to a new location. As such, it can make a second HTTP request to fetch the resource to continue processing the original HTTP request. This is somewhat simpler than a 301 Moved Permanently status code because the client is not expected to take action such as updating internal links.

Note

For backward compatibility, the client may change the HTTP request method from POST to GET for the subsequent HTTP request. However, this is not recommended. To remove ambiguity, the server can return an alternative status code. The 303 See Other status code indicates that the HTTP request must change to a HTTP GET method, whereas the 307 Temporary Redirect status code stipulates that the HTTP request method has to be preserved for the subsequent HTTP request.

Note

Search engines may interpret an URI returning a 302 Found status code over a prolonged period of time as equal to the 301 Moved Permanently status code and treat it as such.

Example

In the example, the client requests a resource that has been temporarily moved. The server indicates the new location and supplies a relevant message that can be displayed on the client-side.

Request

GET /news.html HTTP/1.1
Host: www.example.re

Response

HTTP/1.1 302 Found
Location: http//www.example.re/testing/news.html
Content-Type: text/html
Content-Length: 167

<h1>The Newsfeed has moved</h1>
<body>
The site is currently under development and the newsfeed has temporarily moved to <a href=/testing/news.html>here</a>.
</body>

Code references

.NET

HttpStatusCode.Found

Rust

http::StatusCode::FOUND

Rails

:found

Go

http.StatusFound

Symfony

Response::HTTP_FOUND

Python3.5+

http.HTTPStatus.FOUND

Java

java.net.HttpURLConnection.HTTP_MOVED_TEMP

Apache HttpComponents Core

org.apache.hc.core5.http.HttpStatus.SC_MOVED_TEMPORARILY

Angular

@angular/common/http/HttpStatusCode.Found

Takeaway

The 302 Found status code indicates that the requested resource has been temporarily moved and that a second, otherwise identical HTTP request has to be made to fetch the resource. As the requested resource has moved temporarily, the URI has to be revalidated upon the next time the resource is requested.

See also

  • 303 See Other
  • 307 Temporary Redirect
  • RFC 7231

Last updated: August 2, 2023

Whenever we get a HTTP 302 error, it requires a redirect and the same questions usually arise:

Вот некоторые из вопросов:

  1. Мой сайт готов к этому?
  2. Какой тип перенаправления наиболее подходит для моего случая?
  3. Потеряю ли я всю работу по SEO, которую я сделал до сих пор?
  4. Google накажет меня? Что произойдет, если я устраню перенаправления?
  5. Как они сделаны?
  6. Как исправить ошибку 302? (если это происходит)


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

Code 302 indicates a temporary redirection.
One of the most notable features that differentiate it from a Переадресация 301 в том, что в случае 302 перенаправлений сила SEO не переносится на новый URL.

Google SEO

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

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

Редирект 302 — это код, который сообщает посетителям определенного URL-адреса, что страница была временно перемещена, направляя их непосредственно в новое местоположение.
Другими словами, перенаправление 302 активируется, когда роботы Google или другие поисковые системы запрашивают загрузку определенной страницы. В этот момент, благодаря этому перенаправлению, сервер возвращает автоматический ответ, указывающий новый URL.
Таким образом избегаются ошибки и неприятности как для поисковых систем, так и для пользователей, что гарантирует плавную навигацию.

Для чего нужен редирект 302?

Редирект 302 служит, например, для того, чтобы иметь несколько версий домашней страницы на разных языках.
The main one can be in English, but if the visitors come from other countries then this system automatically redirects them to a page in their language.

Переадресация 302

Таким образом, мобилизация Веб-трафик достигается, но в то же время влияние на уровне SEO главной страницы не ослабляется. Это продолжает расти, несмотря на то, что передача власти не происходит, как мы объясняли ранее.

Пример перенаправления HTTP 302

The most common HTTP 302 redirect example case is Google.
Независимо от страны, в которую вы входите, если вы введете https://www.google.com/, you will be redirected to the Google version in the language/country that corresponds to you.

Поиск в Google
В случае Германии 302 автоматически доставит нас к https://www.google.de/ так что мы можем искать контент на немецком языке.
Порталы успешных компаний, таких как Coca-Cola или даже Fujitsu, также используют эту систему для перенаправления трафика туда, где они считают наиболее удобным.

What causes HTTP 302 error?

Here are some of the most common reasons for the 302 redirect error:

  • Использование 302 перенаправлений во время перемещения домена;
  • Создание перенаправления 302 при перемещении документа;
  • Использование перенаправления 302 во время изменения протокола сайта;
  • Создание 302 перенаправлений при изменении структуры сайта.

HTML-перенаправление 302 не рекомендуется, когда метод исходного запроса должен применяться к запросу целевого URL-адреса — например, перемещение URL-адреса директивы формы, которая использует метод POST для определенного периода.
Вам не следует использовать код состояния 302, если вы хотите перенести SEO-вес на целевой URL.

How to identify HTTP 302 error?

Проверка того, что 301 и 302 перенаправить настройки верны очень легко.
When entering into the address bar of the old address, we observe what is happening.
The change of address indicates that everything is fine with the redirect.
The address remains the same – you need to look for the source of the problem, but first, we advise you to clean the cache and try again.

доменное имя
Есть еще один вариант — подать заявку на проверку кода ответа сервера на онлайн-сервисы, например, http://example.com/e_redirect/.
Если вы правильно настроили перенаправление, после ввода имени домена вы увидите код ответа 301 или 302. Это зависит от того, какой тип перенаправления вы планировали получить изначально.
Некоторые сервисы дополнительно отображают код, предоставленный сервером после перенаправления, и здесь есть только одна допустимая опция — 200 OK.

How to fix HTTP 302 error?

Способ 1: проверьте конфигурацию сервера

Приложение может работать на сервере, который использует одну из этих двух наиболее распространенных программ веб-сервера, Nginx или Apache. На эти два веб-сервера приходится более 84 процентов глобальной программы веб-сервера!
Therefore, the first step in determining the 302 response code is checking the mandatory redirect instructions in the webserver program configuration file.

Для веб-сервера Apache

Шаг 1: Откройте файл .htaccess на сервере.

To identify the webserver, you need to find the key file. If you are using the Apache web server, locate the .htaccess file in your site’s root filesystem.

Файловый менеджер cPanel
Если ваша программа находится на общем хосте, ваше имя пользователя может быть связано, например, с учетной записью хоста. В этом случае, как правило, каталог корня приложения находится по пути:
/home/<username>/public_html/path, thus the .htaccess file is located at /home/<username>/public_html/.htaccess.

Шаг 2: Найдите директивы mod_rewrite

Найдя файл .htaccess, откройте его в текстовом редакторе и найдите строку, которая использует директивы RewriteXXX, принадлежащие модулю Apache mod_rewrite.

mod_rewrite
Однако основная идея заключается в том, что директива RewriteCond описывает текстовую модель, которая сравнивается с зарегистрированным URL. Когда посетитель запрашивает соответствующий URL на сайте, директива RewriteRule, которая отслеживает одну или несколько инструкций RewriteCond, будет фактически перенаправлять запрос на соответствующий URL.
Например, следующее — это простая комбинация RewriteRule и RewriteCond, которая удовлетворяет всем требованиям example.com, но вместо этого вставляет временный редирект в тот же URI во временном домене — example.com:

RewriteEngine в RewriteCond% {HTTP_HOST} ^ пример \ .com $ RewriteRule ^ (. *) $ HTTP://www.teilitary-example.com/$1 [R = 302]

Обратите внимание на дополнительный баннер в нижней части RewriteRule, который ясно показывает, что код ответа должен быть 302, показывая агенту браузера, что это временное перенаправление.

Шаг 3: Сброс директив в файле .htaccess
# НАЧАЛО WordPress RewriteEngine On RewriteBase / RewriteRule ^ index \ .php $ - [L] RewriteCond% {REQUEST_FILENAME}! -F RewriteCond% {REQUEST_FILENAME}! -D RewriteRule. /index.php [L] # END WordPress

Поэтому, если в вашем файле .htaccess вы обнаружите необычную директиву RewriteRule или RewriteCond, которая вам не подходит, попробуйте временно их аннотировать (с префиксом #) и перезапустите веб-сервер, чтобы проверить, решена ли проблема.

Для веб-сервера Nginx

Шаг 1: Откройте файл nginx.conf

конфигурация ngix
Если ваш веб-сервер работает на Nginx, вам следует искать совершенно другой файл конфигурации. Этот файл указан как nginx.conf по умолчанию и находится в одном из общих каталогов, перечисленных ниже:

/ usr / local / nginx / conf, / etc / nginx или, / usr / local / etc / nginx.

Шаг 2: Перепишите директивы в файле nginx.conf

После обнаружения откройте файл nginx.conf в текстовом редакторе и найдите директивы перезаписи, относящиеся к индикатору перенаправления.

HTTP 302 error: 301 scheme
Например, это простая директива блока (объявленная как набор операторов), которая устанавливает виртуальный сервер путем создания временного перенаправления с abc.com на временный-abc.com:

сервер {слушай 80; слушай 443 песни; имя_сервера www.abc.com; переписать ^ / $ http://www.teilitary-abc.com redirect; }

Nginx переписывает директивы параллельно с Apache RewriteRule и
RewriteCond, потому что они обычно содержат более сложные текстовые шаблоны поиска.

Шаг 3: Проверьте политику замены файла nginx.conf

В любом случае проверьте файл nginx.conf для политики замены исключений, которая содержит флаг перенаправления (другой код ответа возврата постоянного ключа 301).

HTTP 302 error: nginx parameters
Обратите внимание на любые исключения перед перезагрузкой сервера, чтобы проверить, решена ли проблема.

Способ 2: поиск устаревшего программного обеспечения

В документе спецификации RFC для HTTP 1.0 говорится, что цель кода ответа «302 найдено» предназначена для указания того, что клиент должен выполнить временное перенаправление.

HTTP 302 error: device risk
However, many new browsers will process the code 302 received through the POST request as an invalid GET request.
This has triggered snags and confusion with particular web server programs that attempt to force the browser to perform the right work when it needs to be redirected temporarily.
Чтобы решить эту проблему, документ спецификации RFC HTTP 1.1 возвратил 303 кода ответа, еще 307 временных перенаправлений, что является понятным способом управления POST-to-GET или временными переходными ответами.

Метод 3: Очистка бревен

Почти все веб-приложения хранят записи на сервере. Журнал приложения обычно представляет историю приложения, например, какие страницы, серверы были запрошены и подключены, которые были получены из предоставленной базы данных и т. Д.

HTTP 302 error: clean the logs
Журналы сервера подключены к текущему устройству, на котором запускаются программы, и обычно содержат информацию о состоянии и работоспособности всех подключенных служб и даже информацию о сервере.
Запишите Google [PLATFORM_NAME] в CMS или используйте [PROGRAMMING_LANGUAGE], чтобы зарегистрироваться и зарегистрировать [OPERATING_SYSTEM] при запуске пользовательского приложения для получения дополнительной информации для получения этих записей.

Способ 4: исправить код приложения

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

HTTP 302 error: web browser
Попробуйте определить причину проблемы, вручную обнаружив приложение и проанализировав его в файлах журнала сервера и приложений.
Рекомендуется скопировать полное приложение на локальный компьютер для разработки и пройти по нему, чтобы точно узнать, что происходит с 302 сканированием, и увидеть код для каждого приложения.

HTTP 302 Error: Conclusion

Наконец, как вы видели, нам не нужно сильно бояться ошибок перенаправления HTTP 302. Не углубляясь в это, они представляют собой фантастический способ избежать потери трафика на наших веб-страницах с неизбежными изменениями, которые возникают в течение многих лет.
I hope that, after reading this article, you will not get chills every time about how do I fix the 302 moved temporarily error.
Если вы хотите внести свой вклад в сообщение, или если у вас есть вопрос или просто хотите высказать свое мнение, не стесняйтесь комментировать ниже!

Понравилась статья? Поделить с друзьями:
  • Ошибка 300f форд фокус
  • Ошибка 302 php
  • Ошибка 3010 пежо 3008
  • Ошибка 3009 сбербанк
  • Ошибка 30089 13