【问题标题】:Right way to enable requests with method DELETE in nginx在 nginx 中使用 DELETE 方法启用请求的正确方法
【发布时间】:2017-11-26 03:51:48
【问题描述】:

我正在用 PHP 编写一个 RESTful 应用程序,并为 nginx 启用了 DELETE、PUT 请求。

    location / {
        root   html;
        index  index.php index.html index.htm;
        dav_methods PUT DELETE;
    }

当我使用 DELETE 方法执行 REST 请求时,我想在 index.php 中处理 - nginx 删除了 html 文件夹。

告诉 nginx 将 DELETE 请求传递给我的 index.php 的正确方法是什么?

【问题讨论】:

    标签: rest nginx


    【解决方案1】:

    Nginx 不会禁用 PUT 或 DELETE 请求,但它不允许文件夹索引上的这些请求。实际上没有什么需要用 nginx 启用(你应该删除 dav_methods 行),但你需要避免通过 index 指令访问你的 index.php,例如:

    index  index.php index.html index.htm;
    

    改为使用 try_files 来匹配 index.php 文件,例如:

    try_files $uri /index.php$is_args$args;
    

    在这种情况下,nginx 不会抱怨你的 DELETE 方法。

    【讨论】:

      【解决方案2】:

      NginX 直接执行这些 HTTP 方法(DELETE、PUT),甚至不需要调用 PHP 引擎,因为它们是由 nginX 内部的 DAV 扩展处理的。 为了解决这个问题,您可以对所有 API 调用使用 POST HTTP 方法,但添加额外的自定义标头以指示实际的 REST 方法 - 而不是这个

      PUT /api/Person/4 HTTP/1.1
      Host: localhost:10320
      Content-Type: application/json
      Cache-Control: no-cache
      

      你会调用这个

      POST /api/Person/4 HTTP/1.1
      Host: localhost:10320
      Content-Type: application/json
      X-REST-Method: PUT
      Cache-Control: no-cache
      

      然后在 PHP 中你会以这种方式检查

      if($_SERVER['HTTP_X_REST_METHOD']!='')
      switch($_SERVER['HTTP_X_REST_METHOD'])
      {
        case 'PUT':
          ...
          break;
        case 'PATCH':
          ...
          break;
        case 'DELETE':
          ...
          break;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 2018-09-15
        • 2018-04-27
        • 2011-12-23
        相关资源
        最近更新 更多