在 nginx 中使用方法 DELETE 启用请求的正确方法
Right way to enable requests with method DELETE in nginx
我在 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 的正确方法是什么?
NginX 直接执行那些 HTTP 方法(DELETE、PUT),甚至不调用 PHP 引擎,因为它们由 nginX 中的 DAV 扩展处理。
要解决此问题,您可以对所有 API 调用使用 POST HTTP 方法,但添加额外的自定义 header 以指示实际的 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;
}
Nginx 不会禁用 PUT 或 DELETE 请求,但它不允许对文件夹索引发出这些请求。 nginx 不需要启用任何东西(你应该删除 dav_methods 行),但你需要避免通过索引指令访问你的 index.php ,如:
index index.php index.html index.htm;
而是使用 try_files 来匹配 index.php 文件,例如:
try_files $uri /index.php$is_args$args;
在这种情况下,nginx 不会抱怨您的 DELETE 方法。
我在 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 的正确方法是什么?
NginX 直接执行那些 HTTP 方法(DELETE、PUT),甚至不调用 PHP 引擎,因为它们由 nginX 中的 DAV 扩展处理。 要解决此问题,您可以对所有 API 调用使用 POST HTTP 方法,但添加额外的自定义 header 以指示实际的 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;
}
Nginx 不会禁用 PUT 或 DELETE 请求,但它不允许对文件夹索引发出这些请求。 nginx 不需要启用任何东西(你应该删除 dav_methods 行),但你需要避免通过索引指令访问你的 index.php ,如:
index index.php index.html index.htm;
而是使用 try_files 来匹配 index.php 文件,例如:
try_files $uri /index.php$is_args$args;
在这种情况下,nginx 不会抱怨您的 DELETE 方法。