nginx rewrite post data

2019-02-17 17:19发布

I need to preserve the POST data to a different url

The rewrite works but the post data is lost

need to post data from user_info.php to userhistory

 location  ~ user_info.php {
  rewrite ^/.* http://testing.com/userhistory  permanent;
 }

The data is lost. How can I preserve the data?

3条回答
疯言疯语
2楼-- · 2019-02-17 17:27

In my conf I use try_files with regex

for example

location /yourfolder/(?<specialRequest>.*) {
    try_files $uri /yourfolder/index.php?r=$specialRequest;
    return 307 https://$host/yourfolder/index.php?r=$specialRequest; // it also work
}
查看更多
混吃等死
3楼-- · 2019-02-17 17:41

Basically, you want to automatically redirect a POST request using a 301 Moved Permanently redirect.

However. such redirect are specifically disallowed by the HTTP Specifications which states that:

If the 301 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.

The specs also note that:

When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.

I believe the second situation may be what is going on and that while the target server is expecting POST data, it is receiving GET data instead.

Your choices are:

A. Change the code to work with GET data or better still, both POST and GET. I.E., look for POST and if not there, try GET equivalents.

B. Try to ensure the code receives POST data by working with the Spec.

You may be able to achieve Choice B by using the proxy_pass directive to handle the request instead.

Something such as:

location  ~ user_info.php {
    proxy_pass http://testing.com/userhistory;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

In this way, the user is technically not being redirected.

查看更多
We Are One
4楼-- · 2019-02-17 17:41

You just need to write a Nginx rewrite rule with HTTP status code 307 or 308:

location  ~ user_info.php {
  return 307 http://testing.com/userhistory;
}

Http Status code 307 or 308 should be used instead of 301 because it changes the request method from POST to GET. Refer https://tools.ietf.org/id/draft-reschke-http-status-308-07.html#introduction

Also redirecting via return is better compared to rewrite according to nginx doc: https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites

查看更多
登录 后发表回答