HTTP код перенаправления 302 Found
означает, что запрошенный ресурс был временно перемещён по адресу, указанному в заголовке Location
(en-US). Получив такой ответ браузер перенаправляется на новую страницу, но поисковые системы не обновляют свои ссылки на ресурс (в жаргоне SEO говорят, что вес ссылки (link-juice) не меняется и не отправляется на новый URL-адрес).
Несмотря на требование спецификации не изменять при перенаправлении метод и тело запроса, не все программные клиенты выполняют его, и с некоторыми из них можно столкнуться до сих пор. Поэтому рекомендуется установить код 302
только как ответ для методов GET
или HEAD
. Для остальных случаев лучше использовать код 307 Temporary Redirect
, поскольку в этом случае изменение метода явно запрещено.
В тех случаях, когда вы хотите, чтобы используемый метод был изменён на GET
, используйте код 303 See Other
. Это полезно, если вы хотите дать ответ на метод PUT
, который не является загруженным ресурсом, но является подтверждающим сообщением (например, «Вы успешно загрузили XYZ»).
Статус
Пример
Запрос клиента
GET / HTTP/1.1 Host: www.example.org
Ответ сервера
HTTP/1.1 302 Found Location: http://www.example.org/index.asp
Спецификации
Спецификация | Название |
---|---|
RFC 7231, секция 6.4.3: 302 Found | Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content |
Совместимость с браузером
BCD tables only load in the browser
Смотрите также
307 Temporary Redirect
, эквивалент рассматриваемого кода ответа, но явно запрещающий изменение метода запроса.303 See Other
, временное перенаправление, которое изменяет метод запроса наGET
.301 Moved Permanently
, постоянное перенаправление.
HTTP 302 codes are a valuable way to redirect website users to a different URL temporarily. However, if your website is delivering 302 redirects in error, it’s a sign that something’s wrong.
Don’t worry — you can fix this problem — but you’ll need to do some troubleshooting.
The first step is to understand precisely what HTTP 302 codes are, how they work, and why they occur. Once you know that, you can figure out what’s gone wrong and how to make it right.
In this post, we’ll tell you everything you need to know about HTTP 302 errors. Then we’ll share five troubleshooting tips to help you fix them.
Let’s get started!
Check Out Our Video Guide to The 302 HTTP Status Code
What Are HTTP 302 Status Codes?
302 codes are a specific type of HTTP status code. These codes are like “notes” that a server delivers to your browser.
Whenever you click on a link or navigate to a URL, your browser requests the webserver for the same. In return, the server sends back the relevant resource (e.g. the page you’re trying to access) along with an HTTP header. The HTTP status codes are inside that header.
Typically, you can’t see these status codes anywhere on the web page. You’ll only usually see them when an error occurs, or if you’ve installed a browser extension that makes them visible:
3xx status codes (301, 302, etc.) are a class of status codes called “redirection codes.” They’re returned whenever the server sends back a new resource instead of the requested resource.
In other words, they’re shown when the website page you intended to access redirects you to a different page.
The critical difference between code 301 and code 302 is that the former is used for permanent redirects, whereas the latter is for temporary redirects.
The 301 redirects also pass “link juice,” whereas 302s don’t. That has a significant impact on Search Engine Optimization (SEO).
Uh oh… you’ve just seen an HTTP 302 code pop up. 😬 Now what? 🤷♀️ Start with this thorough guide ⤵Click to Tweet
How 302 Redirects Work
When you set up a 302 redirect for a page on your website that’s temporarily unavailable, and a user visits that page, your webserver will respond to the visitor’s browser with a special Location header. This header will indicate the new URL that the browser should redirect the user to instead.
For example, imagine that a user types blog.example.com into their browser URL bar, but the website is configured to redirect it to blogging.example.com.
The server response will include both the 302 status code and the Location: blogging.example.com header. This setting tells the user’s browser to redirect this request to the new URL instead.
Of course, all of this happens automatically and behind the scenes. The user shouldn’t be able to see any of this play out. Instead, their browser should automatically take them to the new resource.
Why HTTP 302 Errors Happen
If something is misconfigured on your website, it might cause 302 codes to be issued in error. If this happens, you may run into problems such as:
- A page on your website that redirects your visitors elsewhere when it shouldn’t
- A page on your website that redirects your visitors to the wrong resource
- The ERR_TOO_MANY_REDIRECTS error (also known as a “redirect loop”)
The last of these issues is the only one that will display an actual error page. If you’re using the Chrome browser, a redirect loop error page will look something like this:
On Mozilla Firefox, it looks like this:
All of the above problems are caused by some misconfiguration. It may be a plugin conflict, incorrect URL settings, or a misconfigured .htaccess file.
How to Fix the HTTP 302 Error (5 Methods)
Next, we’ll walk you through five troubleshooting methods that can help you figure out what’s causing the problem and fix it.
Before we get started, make sure to perform a complete backup of your website first. That way, if anything goes wrong, you can always revert to the previous version. You can use a WordPress plugin to do this.
1. Determine Whether the Redirects Are Valid
302 responses are usually not errors. Temporarily redirecting users to a different page can be a valid configuration and isn’t usually something that requires fixing.
It’s only an error if your website is responding with 302 codes that it shouldn’t be issuing, or if it’s causing a redirect loop. Therefore, the first step is to double-check which URLs are generating the HTTP 302 codes and determine whether the redirect is appropriate or not.
To do so, you can navigate to the pages on your website you suspect of issuing the 302 error and see for yourself if they behave as expected. If a temporarily unavailable page redirects to the correct resource, it’s appropriately configured.
However, if a page redirects you to the wrong resource or your browser reports a redirect loop by bringing up an ERR_TOO_MANY_REDIRECTS error page, it’s a sign that one (or more) of your redirects isn’t configured quite right.
2. Check Your Plugins
One of the most common causes of 302 errors and redirect loops is plugins.
Some WordPress redirect manager plugins and SEO tools like Yoast SEO manage your website redirects for you and enable you to set up redirect rules:
If these rules are misconfigured, or if two plugins conflict, it can cause unexpected issues. Therefore, you’ll need to check each relevant tool that’s installed on your site.
For example, if you’re using the popular 301 Redirects WordPress plugin, you can check the configuration by navigating to Settings > 301 Redirects. Under Redirect Rules, you’ll see a list of all the redirect rules you’ve set up:
Check all the 302 redirects listed here, and make sure they’re all correct.
You’ll also want to ensure that you haven’t set up anything in a way that could cause a redirect loop. For example, if Page-A is set to redirect to Page-B, but Page-B is also set to redirect to Page-A, this will cause an error.
If you have multiple redirect manager plugins and you’re not sure which one is causing the issue, you can try deactivating them one by one from the WordPress Plugins page (be sure to make a backup first):
After deactivating each plugin, try revisiting the problem URL to see if the 302 error persists.
If the problem is suddenly fixed, you’ll know which plugin was causing the issue, and you can then choose to troubleshoot further or remove it from your site.
3. Ensure That Your WordPress URL Settings Are Configured Correctly
Another common cause of the HTTP 302 error is a misconfiguration in the WordPress URL settings.
To check this, navigate to Settings > General in your WordPress dashboard. Here, you should see a WordPress Address (URL) field and a Site Address (URL) field:
In most cases, the URLs in both of these fields should match. Make sure they’re both the same, including the “www” portion (or lack thereof) before the domain name.
If they don’t match, update the settings, then check the URL of the page issuing the HTTP 302 error to see if it’s fixed.
4. Check Your Server Configuration
A misconfigured server can also sometimes cause 302 redirect errors. Therefore, the next step is to check your server configuration.
If your host uses the Apache webserver, you can do this by checking your.htaccess file.
First, connect to your site’s server via a control dashboard like cPanel or an FTP client. Then navigate to the root directory of your site — the same place as the wp-admin and wp-content folders — and find the .htaccess file:
If you aren’t finding the .htaccess file here (and you’re sure on an Apache server), you may need to tell FileZilla to show hidden files before it’ll appear in the file list.
Next, open the file in your favorite text editor. It should look something like this:
Now, we’re going to look for RewriteXXX
directives (the highlighted elements above). Without getting too technical, RewriteCond
and RewriteRule
directives are used to perform redirections from one URL to another.
The RewriteCond
directive specifies the URL you want to redirect the visitor away from, while the RewriteRule directive specifies the URL you want to redirect them to. Here’s an example:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^website.com$
RewriteRule ^(.*)$ http://www.temporary-website.com/$1 [R=302]
The flag at the end, “[R=302]”, tells the browser that this is a temporary 302 redirect.
If you notice any RewriteXXX combinations similar to the above in your .htaccess file that shouldn’t be there, you can comment them out, save the changes, and reload the problem web page to see if it resolves the issue.
Just make sure to download and save a spare copy of your .htaccess file before you make any changes in case something goes wrong.
5. Speak to Your Web Host
If you’ve tried all of the above methods and you’re still having trouble, the next step is to speak to your web host.
Troubleshooting a 302 code error beyond this point requires a lot of technical know-how. Therefore, unless you’re a professional developer, it’s probably best to get help from an expert.
At Kinsta, we take support seriously. Our team of experts is always on-hand to help you resolve issues like this whenever they arise:
We’re available 24/7. All you have to do is log in to your MyKinsta account and contact us via live chat to connect with a support engineer who can help in real-time.
Don’t let HTTP 302 codes slow your roll. 🙅♀️ Learn how to resolve them with these 5 troubleshooting tips 💥Click to Tweet
Summary
HTTP 302 status codes are a completely normal way to redirect your website visitors. However, they should only be used when the resource page is temporarily unavailable.
Suppose your website is issuing 302 codes in error or causing redirect loops. In that case, it’s vital to fix this problem as soon as possible, or it may negatively impact your SEO and conversions.
You can follow these five steps to fix HTTP 302 errors on your website:
- Determine whether the redirects are appropriate or not by examining the URLs that are issuing the 302 redirects.
- Check your plugins to make sure any redirect settings are valid.
- Ensure that your WordPress URL settings are configured correctly.
- Check your server configuration by looking for incorrect
RewriteXXX
directives in your .htaccess file (Apache servers only). - Speak to your web host for further technical support if the problem persists.
Do you have any questions left about the HTTP 302 error? Let us know in the comments section.
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
HTTP 302 codes are a valuable way to redirect website users to a different URL temporarily. However, if your website is delivering 302 redirects in error, it’s a sign that something’s wrong.
Don’t worry — you can fix this problem — but you’ll need to do some troubleshooting.
The first step is to understand precisely what HTTP 302 codes are, how they work, and why they occur. Once you know that, you can figure out what’s gone wrong and how to make it right.
In this post, we’ll tell you everything you need to know about HTTP 302 errors. Then we’ll share five troubleshooting tips to help you fix them.
Let’s get started!
Check Out Our Video Guide to The 302 HTTP Status Code
What Are HTTP 302 Status Codes?
302 codes are a specific type of HTTP status code. These codes are like “notes” that a server delivers to your browser.
Whenever you click on a link or navigate to a URL, your browser requests the webserver for the same. In return, the server sends back the relevant resource (e.g. the page you’re trying to access) along with an HTTP header. The HTTP status codes are inside that header.
Typically, you can’t see these status codes anywhere on the web page. You’ll only usually see them when an error occurs, or if you’ve installed a browser extension that makes them visible:
3xx status codes (301, 302, etc.) are a class of status codes called “redirection codes.” They’re returned whenever the server sends back a new resource instead of the requested resource.
In other words, they’re shown when the website page you intended to access redirects you to a different page.
The critical difference between code 301 and code 302 is that the former is used for permanent redirects, whereas the latter is for temporary redirects.
The 301 redirects also pass “link juice,” whereas 302s don’t. That has a significant impact on Search Engine Optimization (SEO).
Uh oh… you’ve just seen an HTTP 302 code pop up. 😬 Now what? 🤷♀️ Start with this thorough guide ⤵Click to Tweet
How 302 Redirects Work
When you set up a 302 redirect for a page on your website that’s temporarily unavailable, and a user visits that page, your webserver will respond to the visitor’s browser with a special Location header. This header will indicate the new URL that the browser should redirect the user to instead.
For example, imagine that a user types blog.example.com into their browser URL bar, but the website is configured to redirect it to blogging.example.com.
The server response will include both the 302 status code and the Location: blogging.example.com header. This setting tells the user’s browser to redirect this request to the new URL instead.
Of course, all of this happens automatically and behind the scenes. The user shouldn’t be able to see any of this play out. Instead, their browser should automatically take them to the new resource.
Why HTTP 302 Errors Happen
If something is misconfigured on your website, it might cause 302 codes to be issued in error. If this happens, you may run into problems such as:
- A page on your website that redirects your visitors elsewhere when it shouldn’t
- A page on your website that redirects your visitors to the wrong resource
- The ERR_TOO_MANY_REDIRECTS error (also known as a “redirect loop”)
The last of these issues is the only one that will display an actual error page. If you’re using the Chrome browser, a redirect loop error page will look something like this:
On Mozilla Firefox, it looks like this:
All of the above problems are caused by some misconfiguration. It may be a plugin conflict, incorrect URL settings, or a misconfigured .htaccess file.
How to Fix the HTTP 302 Error (5 Methods)
Next, we’ll walk you through five troubleshooting methods that can help you figure out what’s causing the problem and fix it.
Before we get started, make sure to perform a complete backup of your website first. That way, if anything goes wrong, you can always revert to the previous version. You can use a WordPress plugin to do this.
1. Determine Whether the Redirects Are Valid
302 responses are usually not errors. Temporarily redirecting users to a different page can be a valid configuration and isn’t usually something that requires fixing.
It’s only an error if your website is responding with 302 codes that it shouldn’t be issuing, or if it’s causing a redirect loop. Therefore, the first step is to double-check which URLs are generating the HTTP 302 codes and determine whether the redirect is appropriate or not.
To do so, you can navigate to the pages on your website you suspect of issuing the 302 error and see for yourself if they behave as expected. If a temporarily unavailable page redirects to the correct resource, it’s appropriately configured.
However, if a page redirects you to the wrong resource or your browser reports a redirect loop by bringing up an ERR_TOO_MANY_REDIRECTS error page, it’s a sign that one (or more) of your redirects isn’t configured quite right.
2. Check Your Plugins
One of the most common causes of 302 errors and redirect loops is plugins.
Some WordPress redirect manager plugins and SEO tools like Yoast SEO manage your website redirects for you and enable you to set up redirect rules:
If these rules are misconfigured, or if two plugins conflict, it can cause unexpected issues. Therefore, you’ll need to check each relevant tool that’s installed on your site.
For example, if you’re using the popular 301 Redirects WordPress plugin, you can check the configuration by navigating to Settings > 301 Redirects. Under Redirect Rules, you’ll see a list of all the redirect rules you’ve set up:
Check all the 302 redirects listed here, and make sure they’re all correct.
You’ll also want to ensure that you haven’t set up anything in a way that could cause a redirect loop. For example, if Page-A is set to redirect to Page-B, but Page-B is also set to redirect to Page-A, this will cause an error.
If you have multiple redirect manager plugins and you’re not sure which one is causing the issue, you can try deactivating them one by one from the WordPress Plugins page (be sure to make a backup first):
After deactivating each plugin, try revisiting the problem URL to see if the 302 error persists.
If the problem is suddenly fixed, you’ll know which plugin was causing the issue, and you can then choose to troubleshoot further or remove it from your site.
3. Ensure That Your WordPress URL Settings Are Configured Correctly
Another common cause of the HTTP 302 error is a misconfiguration in the WordPress URL settings.
To check this, navigate to Settings > General in your WordPress dashboard. Here, you should see a WordPress Address (URL) field and a Site Address (URL) field:
In most cases, the URLs in both of these fields should match. Make sure they’re both the same, including the “www” portion (or lack thereof) before the domain name.
If they don’t match, update the settings, then check the URL of the page issuing the HTTP 302 error to see if it’s fixed.
4. Check Your Server Configuration
A misconfigured server can also sometimes cause 302 redirect errors. Therefore, the next step is to check your server configuration.
If your host uses the Apache webserver, you can do this by checking your.htaccess file.
First, connect to your site’s server via a control dashboard like cPanel or an FTP client. Then navigate to the root directory of your site — the same place as the wp-admin and wp-content folders — and find the .htaccess file:
If you aren’t finding the .htaccess file here (and you’re sure on an Apache server), you may need to tell FileZilla to show hidden files before it’ll appear in the file list.
Next, open the file in your favorite text editor. It should look something like this:
Now, we’re going to look for RewriteXXX
directives (the highlighted elements above). Without getting too technical, RewriteCond
and RewriteRule
directives are used to perform redirections from one URL to another.
The RewriteCond
directive specifies the URL you want to redirect the visitor away from, while the RewriteRule directive specifies the URL you want to redirect them to. Here’s an example:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^website.com$
RewriteRule ^(.*)$ http://www.temporary-website.com/$1 [R=302]
The flag at the end, “[R=302]”, tells the browser that this is a temporary 302 redirect.
If you notice any RewriteXXX combinations similar to the above in your .htaccess file that shouldn’t be there, you can comment them out, save the changes, and reload the problem web page to see if it resolves the issue.
Just make sure to download and save a spare copy of your .htaccess file before you make any changes in case something goes wrong.
5. Speak to Your Web Host
If you’ve tried all of the above methods and you’re still having trouble, the next step is to speak to your web host.
Troubleshooting a 302 code error beyond this point requires a lot of technical know-how. Therefore, unless you’re a professional developer, it’s probably best to get help from an expert.
At Kinsta, we take support seriously. Our team of experts is always on-hand to help you resolve issues like this whenever they arise:
We’re available 24/7. All you have to do is log in to your MyKinsta account and contact us via live chat to connect with a support engineer who can help in real-time.
Don’t let HTTP 302 codes slow your roll. 🙅♀️ Learn how to resolve them with these 5 troubleshooting tips 💥Click to Tweet
Summary
HTTP 302 status codes are a completely normal way to redirect your website visitors. However, they should only be used when the resource page is temporarily unavailable.
Suppose your website is issuing 302 codes in error or causing redirect loops. In that case, it’s vital to fix this problem as soon as possible, or it may negatively impact your SEO and conversions.
You can follow these five steps to fix HTTP 302 errors on your website:
- Determine whether the redirects are appropriate or not by examining the URLs that are issuing the 302 redirects.
- Check your plugins to make sure any redirect settings are valid.
- Ensure that your WordPress URL settings are configured correctly.
- Check your server configuration by looking for incorrect
RewriteXXX
directives in your .htaccess file (Apache servers only). - Speak to your web host for further technical support if the problem persists.
Do you have any questions left about the HTTP 302 error? Let us know in the comments section.
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
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:
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 theLocation
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 fromPOST
toGET
for the subsequent request. If
this behavior is undesired, the307
(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 Permanently302
: Found307
: Temporary Redirect308
: 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]
- ^ Lawrence, Eric. «HTTP Methods and Redirect Status Codes». EricLaw’s IEInternals blog. Retrieved 2011-08-20.
- ^ «Request and response objects | Django documentation | Django». Docs.djangoproject.com. Retrieved 2014-06-23.
- ^ «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)
If you’ve spent any time on the internet, chances are you’ve encountered an HTTP status code.
In simple terms, HTTP status codes are standard response codes that show the relationship between all the things that go on in the background when you travel from web page to web page. Things like the user agent (i.e., your web browser), the server, the web page you’re trying to load, and any third-party web applications you might be running.
Because of the complexity of how all those elements interact, there are many possible HTTP status codes you can run up against.
HTTP status codes identify and diagnose the particular blocker preventing you from loading a resource, and can give you information about the journey you took on the way to a page.
In this article, we’ll cover what you need to know about the HTTP 302 status code – jargon-free.
What is an HTTP 302?
The 302 status code is a redirection message that occurs when a resource or page you’re attempting to load has been temporarily moved to a different location. It’s usually caused by the web server and doesn’t impact the user experience, as the redirect happens automatically.
For starters, it’s helpful to know that all HTTP messages with 3xx are redirection messages.
Say blog.hubspot.com no longer exists, and the content is now permanently housed on blogging.hubspot.com. This would trigger a 301 status code, which indicates a permanent redirection from one location to another.
The 302 redirect, on the other hand, is only temporary. A good example of when to use a 302 status code is for localization and language purposes.
For instance, if you visit a clothing website based in the United Kingdom but you are located in the United States. A 302 redirect would send you to the US version of the site to ensure the currency and other content are displayed correctly, according to your location.
You can also use a 302 status code when:
- Redesigning a page – You can send users to a temporary location while the other page is under construction.
- Conducting A/B tests – Want to test a new page and get feedback on its performance? You can do this with a 302 redirect without hurting your ranking.
- Running a promotion – To drive traffic to a particular offer, you can set up a temporary redirect for a page that usually includes other content.
- A product is sold out – In the case of a sold-out or temporarily unavailable product, you can redirect users to a related page until it is available again.
While this list is not exhaustive, here’s the golden rule to keep in mind: Only use a 302 redirect if the change is temporary.
Furthermore, a 302 status code happens on the server-side and shouldn’t be noticed by users if set up correctly. The web server serving up the 302 redirect will immediately indicate the new location of the page to your browser (and search engines) and should send users there right away.
How a 302 Status Code Affects SEO
From an SEO perspective, it’s important to understand how a 302 status code can impact your ranking and when you should use it.
Firstly, if the location of a page has changed and a redirect has not been set up, this can lead to a 404 status error (i.e., your page cannot be found) and affect your ranking. After all, Google won’t want to send users to a page that leads to nowhere.
One benefit of using a redirect like this is that you don’t have to sacrifice your ranking when you temporarily send users elsewhere.
Say you’re using it to redirect users from a sold-out product page to a relevant product page. You wouldn’t want your unavailable product’s page to drop in ranking, just because it’s currently unavailable. With a 302 status code, you can maintain your ranking.
However, this also means that your temporary URL will not benefit from any link juice because Google knows it won’t be there long.
For comparison, a 301 code typically sends most link equity to your new URL, but your page can experience some drop in ranking as a result of the redirect.
How to Identify & Implement an HTTP 302 Error
If you want to see when you’ve encountered a 302 redirect (or any type of redirect), consider using an application or Chrome extension (like this one, Redirect Path). This type of tool will show you directly in your browser when you run into a redirect. Tools like Pulsetic can be used to monitor websites and send alerts for server or website errors.
You can also view and implement the code from the backend by accessing your .htaccess file. To avoid accessing this file, you can also install a redirect manager plugin or an SEO tool that includes a redirect manager (like Yoast SEO Premium).
Overall, you want to make sure you understand how redirection messages affect SEO. A 302 status code can be a great strategy when making temporary changes to your website, like testing new website features and product promotions.
So, when you’re debating between various redirection messages, make sure the one you choose aligns with your long-term strategy.
Код 302 Found не является ошибкой, это информационное сообщение, которое возвращается в ответ на запрос
к временно перемещенному ресурсу. Код Found должен содержать в себе информацию о новом
месторасположении.
О чем свидетельствует ошибка 302
Код 302 устанавливает системный администратор ресурса. При этом в заголовке сообщения Location должен
быть указан новый адрес. Браузер автоматически перенаправляется по указанному url, но при этом поисковые
системы не обновляют ссылки так, как это происходит в случае использования кода 301 Redirect. Вес ссылки
в поисковой системе при этом также не изменяется и не переносится на новый адрес, указанный в заголовке
Location.
Рекомендуется применять этот способ перенаправления в качестве ответа только для некоторых поисковых
методов, в частности:
- GET, при котором все данные передаются в строке запроса;
- HEAD, при котором сервер запрашивает информацию о заголовке искомого ресурса или файла.
Для ответа на запросы, отправленные другими поисковыми методами, при временном перемещении ресурса
рекомендовано применять код 307 Temporary redirect
Что делать пользователю, когда в браузере появляется код ошибки 302
Если вы увидели сообщение 302 Found, прежде всего, посмотрите заголовки, в которых должно содержаться
перенаправление. Если в заголовке нет перенаправления, напишите в техническую поддержку ресурса или
хостинг-провайдера — бывает, что его настраивают по ошибке.
Причины возникновения кода 302 found
Его не настраивают для тех url, которые изменены на постоянной основе. Основная причина использования —
техническое обслуживание сайта, во время которого контент может быть размещен на временном домене.
Главная цель, которую преследует при этом системный администратор — чтобы поисковые системы не начали
индексацию по новому адресу. Иногда не совсем добросовестные администраторы интернет-магазинов
настраивают код 302 для товаров, которых в данный момент нет в наличии.
Вас также может заинтересовать
Содержание
Составили подробный классификатор кодов состояния HTTP. Добавляйте в закладки, чтобы был под рукой, когда понадобится.
Что такое код ответа HTTP
Когда посетитель переходит по ссылке на сайт или вбивает её в поисковую строку вручную, отправляется запрос на сервер. Сервер обрабатывает этот запрос и выдаёт ответ — трехзначный цифровой код HTTP от 100 до 510. По коду ответа можно понять реакцию сервера на запрос.
Первая цифра в ответе обозначает класс состояния, другие две — причину, по которой мог появиться такой ответ.
Как проверить код состояния страницы
Проверить коды ответа сервера можно вручную с помощью браузера и в панелях веб‑мастеров: Яндекс.Вебмастер и Google Search Console.
В браузере
Для примера возьмём Google Chrome.
-
Откройте панель разработчика в браузере клавишей F12, комбинацией клавиш Ctrl + Shift + I или в меню браузера → «Дополнительные инструменты» → «Инструменты разработчика». Подробнее об этом рассказывали в статье «Как открыть исходный код страницы».
-
Переключитесь на вкладку «Сеть» в Инструментах разработчика и обновите страницу:
В Яндекс.Вебмастере
Откройте инструмент «Проверка ответа сервера» в Вебмастере. Введите URL в специальное поле и нажмите кнопку «Проверить»:
Как добавить сайт в Яндекс.Вебмастер и другие сервисы Яндекса
В Google Search Console
Чтобы посмотреть код ответа сервера в GSC, перейдите в инструмент проверки URL — он находится в самом верху панели:
Введите ссылку на страницу, которую хотите проверить, и нажмите Enter. В результатах проверки нажмите на «Изучить просканированную страницу» в блоке «URL есть в индексе Google».
А затем в открывшемся окне перейдите на вкладку «Подробнее»:
Теперь расскажем подробнее про все классы кодов состояния HTTP.
1* класс кодов (информационные сообщения)
Это системный класс кодов, который только информирует о процессе передачи запроса. Такие ответы не являются ошибкой, хотя и могут отображаться в браузере как Error Code.
100 Continue
Этот ответ сообщает, что полученные сведения о запросе устраивают сервер и клиент может продолжать отправлять данные. Такой ответ может требоваться клиенту, если на сервер отправляется большой объём данных.
101 Switching Protocols
Сервер одобрил переключение типа протокола, которое запросил пользователь, и в настоящий момент выполняет действие.
102 Processing
Запрос принят — он находится в обработке, и на это понадобится чуть больше времени.
103 Checkpoint
Контрольная точка — используется в запросах для возобновления после прерывания запросов POST или PUT.
POST отправляет данные на сервер, PUT создает новый ресурс или заменяет существующий данными, представленными в теле запроса.
Разница между ними в том, что PUT работает без изменений: повторное его применение даёт такой же результат, что и в первый раз, а вот повторный вызов одного и того же метода POST часто меняет данные.
Пример — оформленный несколько раз интернет‑заказ. Такое часто происходит как раз по причине неоднократного использования запроса PUT.
105 Name Not Resolved
Не удается преобразовать DNS‑адрес сервера — это означает ошибку в службе DNS. Эта служба преобразует IP‑адреса в знакомые нам доменные имена.
2* класс кодов (успешно обработанные запросы)
Эти коды информируют об успешности принятия и обработки запроса. Также сервер может передать заголовки или тело сообщений.
200 ОК
Все хорошо — HTTP‑запрос успешно обработан (не ошибка).
201 Created
Создано — транзакция успешна, сформирован новый ресурс или документ.
202 Accepted
Принято — запрос принят, но ещё не обработан.
203 Non‑Authoritative Information
Информация не авторитетна — запрос успешно обработан, но передаваемая информация была взята не из первичного источника (данные могут быть устаревшими).
204 No Content
Нет содержимого — запрос успешно обработан, однако в ответе только заголовки без контента сообщения. Не нужно обновлять содержимое документа, но можно применить к нему полученные метаданные.
205 Reset Content
Сбросить содержимое. Запрос успешно обработан — но нужно сбросить введенные данные. Страницу можно не обновлять.
206 Partial Content
Частичное содержимое. Сервер успешно обработал часть GET‑запроса, а другую часть вернул.
GET — метод для чтения данных с сайта. Он говорит серверу, что клиент хочет прочитать какой‑то документ.
Представим интернет‑магазин и страницы каталога. Фильтры, которые выбирает пользователь, передаются благодаря методу GET. GET‑запрос работает с получением данных, а POST‑запрос нужен для отправки данных.
При работе с подобными ответами следует уделить внимание кэшированию.
207 Multi‑Status
Успешно выполнено несколько операций — сервер передал результаты выполнения нескольких независимых операций. Они появятся в виде XML‑документа с объектом multistatus.
226 IM Used
Успешно обработан IM‑заголовок (специальный заголовок, который отправляется клиентом и используется для передачи состояния HTTP).
3* класс кодов (перенаправление на другой адрес)
Эти коды информируют, что для достижения успешной операции нужно будет сделать другой запрос, возможно, по другому URL.
300 Multiple Choices
Множественный выбор — сервер выдает список нескольких возможных вариантов перенаправления (максимум — 5). Можно выбрать один из них.
301 Moved Permanently
Окончательно перемещено — страница перемещена на другой URL, который указан в поле Location.
302 Found/Moved
Временно перемещено — страница временно перенесена на другой URL, который указан в поле Location.
303 See Other
Ищите другую страницу — страница не найдена по данному URL, поэтому смотрите страницу по другому URL, используя метод GET.
304 Not Modified
Модификаций не было — с момента последнего визита клиента изменений не было.
305 Use Proxy
Используйте прокси — запрос к нужному ресурсу можно сделать только через прокси‑сервер, URL которого указан в поле Location заголовка.
306 Unused
Зарезервировано. Код в настоящий момент не используется.
307 Temporary Redirect
Временное перенаправление — запрашиваемый ресурс временно доступен по другому URL.
Этот код имеет ту же семантику, что код ответа 302 Found, за исключением того, что агент пользователя не должен изменять используемый метод HTTP: если в первом запросе использовался POST, то во втором запросе также должен использоваться POST.
308 Resume Incomplete
Перемещено полностью (навсегда) — запрашиваемая страница была перенесена на новый URL, указанный в поле Location заголовка. Метод запроса (GET/POST) менять не разрешается.
4* класс кодов (ошибки на стороне клиента)
Эти коды указывают на ошибки со стороны клиентов.
400 Bad Request
Неверный запрос — запрос клиента не может быть обработан, так как есть синтаксическая ошибка (возможно, опечатка).
401 Unauthorized
Не пройдена авторизация — запрос ещё в обработке, но доступа нет, так как пользователь не авторизован.
Для доступа к запрашиваемому ресурсу клиент должен представиться, послав запрос, включив при этом в заголовок сообщения поле Authorization.
402 Payment Required
Требуется оплата — зарезервировано для использования в будущем. Код предусмотрен для платных пользовательских сервисов, а не для хостинговых компаний.
403 Forbidden
Запрещено — запрос принят, но не будет обработан, так как у клиента недостаточно прав. Может возникнуть, когда пользователь хочет открыть системные файлы (robots, htaccess) или не прошёл авторизацию.
404 Not Found
Не найдено — запрашиваемая страница не обнаружена. Сервер принял запрос, но не нашёл ресурса по указанному URL (возможно, была ошибка в URL или страница была перемещена).
405 Method Not Allowed
Метод не разрешён — запрос был сделан методом, который не поддерживается данным ресурсом. Сервер должен предложить доступные методы решения в заголовке Allow.
406 Not Acceptable
Некорректный запрос — неподдерживаемый поисковиком формат запроса (поисковый робот не поддерживает кодировку или язык).
407 Proxy Authentication Required
Нужно пройти аутентификацию прокси — ответ аналогичен коду 401, только нужно аутентифицировать прокси‑сервер.
408 Request Timeout
Тайм‑аут запроса — запрос клиента занял слишком много времени. На каждом сайте существует свое время тайм‑аута — проверьте интернет‑соединение и просто обновите страницу.
409 Conflict
Конфликт (что‑то пошло не так) — запрос не может быть выполнен из‑за конфликтного обращения к ресурсу (несовместимость двух запросов).
410 Gone
Недоступно — ресурс раньше был размещён по указанному URL, но сейчас удалён и недоступен (серверу неизвестно месторасположение).
411 Length Required
Добавьте длины — сервер отклоняет отправляемый запрос, так как длина заголовка не определена, и он не находит значение Content‑Length.
Нужно исправить заголовки на сервере, и в следующий раз робот сможет проиндексировать страницу.
412 Precondition Failed
Предварительное условие не выполнено — стоит проверить правильность HTTP‑заголовков данного запроса.
413 Request Entity Too Large
Превышен размер запроса — перелимит максимального размера запроса, принимаемого сервером. Браузеры поддерживают запросы от 2 до 8 килобайт.
414 Request‑URI Too Long
Превышена длина запроса — сервер не может обработать запрос из‑за длинного URL. Такая ошибка может возникнуть, например, когда клиент пытается передать чересчур длинные параметры через метод GET, а не POST.
415 Unsupported Media Type
Формат не поддерживается — сервер не может принять запрос, так как данные подгружаются в некорректном формате, и сервер разрывает соединение.
416 Requested Range Not Satisfiable
Диапазон не поддерживается — ошибка возникает в случаях, когда в самом HTTP‑заголовке прописывается некорректный байтовый диапазон.
Корректного диапазона в необходимом документе может просто не быть, или есть опечатка в синтаксисе.
417 Expectation Failed
Ожидания не оправдались — прокси некорректно идентифицировал содержимое поля «Expect: 100‑Continue».
418 I’m a teapot
Первоапрельская шутка разработчиков в 1998 году. В расшифровке звучит как «я не приготовлю вам кофе, потому что я чайник». Не используется в работе.
422 Unprocessable Entity
Объект не обработан — сервер принял запрос, но в нём есть логическая ошибка. Стоит посмотреть в сторону семантики сайта.
423 Locked
Закрыто — ресурс заблокирован для выбранного HTTP‑метода. Можно перезагрузить роутер и компьютер. А также использовать только статистический IP.
424 Failed Dependency
Неуспешная зависимость — сервер не может обработать запрос, так как один из зависимых ресурсов заблокирован.
Выполнение запроса напрямую зависит от успешности выполнения другой операции, и если она не будет успешно завершена, то вся обработка запроса будет прервана.
425 Unordered Collection
Неверный порядок в коллекции — ошибка возникает, если клиент указал номер элемента в неупорядоченном списке или запросил несколько элементов в порядке, отличном от серверного.
426 Upgrade Required
Нужно обновление — в заголовке ответа нужно корректно сформировать поля Upgrade и Connection.
Этот ответ возникает, когда серверу требуется обновление до SSL‑протокола, но клиент не имеет его поддержки.
428 Precondition Required
Нужно предварительное условие — сервер просит внести в запрос информацию о предварительных условиях обработки данных, чтобы выдавать корректную информацию по итогу.
429 Too Many Requests
Слишком много запросов — отправлено слишком много запросов за короткое время. Это может указывать, например, на попытку DDoS‑атаки, для защиты от которой запросы блокируются.
431 Request Header Fields Too Large
Превышена длина заголовков — сервер может и не отвечать этим кодом, вместо этого он может просто сбросить соединение.
Исправляется это с помощью сокращения заголовков и повторной отправки запроса.
434 Requested Host Unavailable
Адрес запрашиваемой страницы недоступен.
444 No Response
Нет ответа — код отображается в лог‑файлах, чтобы подтвердить, что сервер никак не отреагировал на запрос пользователя и прервал соединение. Возвращается только сервером nginx.
Nginx — программное обеспечение с открытым исходным кодом. Его используют для создания веб‑серверов, а также в качестве почтового или обратного прокси‑сервера. Nginx решает проблему падения производительности из‑за роста трафика.
449 Retry With
Повторите попытку — ошибка говорит о необходимости скорректировать запрос и повторить его снова. Причиной становятся неверно указанные параметры (возможно, недостаточно данных).
450 Blocked by Windows Parental Controls
Заблокировано родительским контролем — говорит о том, что с компьютера попытались зайти на заблокированный ресурс. Избежать этой ошибки можно изменением параметров системы родительского контроля.
451 Unavailable For Legal Reasons
Недоступно по юридическим причинам — доступ к ресурсу закрыт, например, по требованию органов государственной власти или по требованию правообладателя в случае нарушения авторских прав.
456 Unrecoverable Error
Неустранимая ошибка — при обработке запроса возникла ошибка, которая вызывает некорректируемые сбои в таблицах баз данных.
499 Client Closed Request
Запрос закрыт клиентом — нестандартный код, используемый nginx в ситуациях, когда клиент закрыл соединение, пока nginx обрабатывал запрос.
5* класс кодов (ошибки на стороне сервера)
Эти коды указывают на ошибки со стороны серверов.
При использовании всех методов, кроме HEAD, сервер должен вернуть в теле сообщения гипертекстовое пояснение для пользователя. И его можно использовать в работе.
500 Internal Server Error
Внутренняя ошибка сервера — сервер столкнулся с неким условием, из‑за которого не может выполнить запрос.
Проверяйте, корректно ли указаны директивы в системных файлах (особенно htaccess) и нет ли ошибки прав доступа к файлам. Обратите внимание на ошибки внутри скриптов и их медленную работу.
501 Not Implemented
Не выполнено — код отдается, когда сам сервер не может идентифицировать метод запроса.
Сами вы эту ошибку не исправите. Устранить её может только сервер.
502 Bad Gateway
Ошибка шлюза — появляется, когда сервер, выступая в роли шлюза или прокси‑сервера, получил ответное сообщение от вышестоящего сервера о несоответствии протоколов.
Актуально исключительно для прокси и шлюзовых конфигураций.
503 Service Unavailable
Временно не доступен — сервер временно не имеет возможности обрабатывать запросы по техническим причинам (обслуживание, перегрузка и прочее).
В поле Retry‑After заголовка сервер укажет время, через которое можно повторить запрос.
504 Gateway Timeout
Тайм‑аут шлюза — сервер, выступая в роли шлюза или прокси‑сервера, не получил ответа от вышестоящего сервера в нужное время.
Исправить эту ошибку самостоятельно не получится. Здесь дело в прокси, часто — в веб‑сервере.
Первым делом просто обновите веб‑страницу. Если это не помогло, нужно почистить DNS‑кэш. Для этого нажмите горячие клавиши Windows+R и введите команду cmd (Control+пробел). В открывшемся окне укажите команду ipconfig / flushdns и подтвердите её нажатием Enter.
505 HTTP Version Not Supported
Сервер не поддерживает версию протокола — отсутствует поддержка текущей версии HTTP‑протокола. Нужно обеспечить клиента и сервер одинаковой версией.
506 Variant Also Negotiates
Неуспешные переговоры — с такой ошибкой сталкиваются, если сервер изначально настроен неправильно. По причине ошибочной конфигурации выбранный вариант указывает сам на себя, из‑за чего процесс и прерывается.
507 Insufficient Storage
Не хватает места для хранения — серверу недостаточно места в хранилище. Нужно либо расчистить место, либо увеличить доступное пространство.
508 Loop Detected
Обнаружен цикл — ошибка означает провал запроса и выполняемой операции в целом.
509 Bandwidth Limit Exceeded
Превышена пропускная способность — используется при чрезмерном потреблении трафика. Владельцу площадки следует обратиться к своему хостинг‑провайдеру.
510 Not Extended
Не продлён — ошибка говорит, что на сервере отсутствует нужное для клиента расширение. Чтобы исправить проблему, надо убрать часть неподдерживаемого расширения из запроса или добавить поддержку на сервер.
511 Network Authentication Required
Требуется аутентификация — ошибка генерируется сервером‑посредником, к примеру, сервером интернет‑провайдера, если нужно ввести пароль для получения доступа к сети через платную точку доступа.