Redirect after POST request

    Every web developer knows that after a POST submit of a form it is advisable to make a redirect to prevent the data from being sent again when the user wants to refresh the page. Basically, this is a critical operation, since form data can be stored in a database or participate in a payment transaction. And then the data is not only duplicated, but extra money will be written off.

    But it’s not about money, but about the right redirect ...

    Almost all web applications when redirecting a POST request return the status of 302 Found. For example, in php, a redirect is done like this: header ('Location: / new / location') ;. Without additional parameters or unless another status is specified separately, the function will return exactly 302 Found.

    Now let's turn to the official documents. RFC 2616 says the following:
    If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

    If the status 302 is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request until it is confirmed by the user, as this may violate the conditions of the request.

    In the same notes, it is written that in spite of this, many user agents neglect this rule and interpret 302 status as 303. But this has gone since the time of HTTP / 1.0, in which 303 status did not exist yet.

    Those. To redirect a POST request, you need to use the 303 See Other status, which is specifically designed for this. In php, a redirect will look, for example, like this: header ('Location: / new / location', true, 303);

    In the RFC, the status note 303 says:
    Many pre-HTTP / 1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303

    Many pre-HTTP / 1.1 user agents do not understand 303 status. If compatibility with such clients is important, then you can use 302 status instead, since most of these agents respond to 302 status as well as 303.

    And you get two options:
    1. Still use 302;
    a. there is a chance of running into a user agent who honors the specification and issues a warning.
    b. since this behavior is not standard, you can run into a generally unpredictable result.

    2. Use 303, then old customers will not understand what they want from them.

    In the second case, you can analyze the protocol version requested by the client and issue 302 for old clients. In the response body write a link to the new URL. Then the user of the old agent can at least click on the link.

    Also popular now: