nginx rewrite post data

前端 未结 3 1235
时光说笑
时光说笑 2020-12-18 02:34

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

相关标签:
3条回答
  • 2020-12-18 02: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.

    0 讨论(0)
  • 2020-12-18 02:46

    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

    0 讨论(0)
  • 2020-12-18 03:01

    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
    }
    
    0 讨论(0)
提交回复
热议问题