Nginx可以通过多种方式实现基于HTTP请求方法(GET, POST, PUT, DELETE等)的访问控制。以下是几种常见的实现方法:
location /api/ {
# 只允许GET和POST方法
if ($request_method !~ ^(GET|POST)$ ) {
return 405; # Method Not Allowed
}
# 其他配置...
}
location /protected/ {
# 只允许GET和HEAD方法
limit_except GET HEAD {
deny all;
}
# 其他配置...
}
map $request_method $is_allowed_method {
default 0;
GET 1;
POST 1;
HEAD 1;
OPTIONS 1;
}
server {
location /restricted/ {
if ($is_allowed_method = 0) {
return 405;
}
# 其他配置...
}
}
location /api/ {
# GET请求转发到一组服务器
if ($request_method = GET) {
proxy_pass http://get_backend;
}
# POST请求转发到另一组服务器
if ($request_method = POST) {
proxy_pass http://post_backend;
}
# 其他方法返回405
return 405;
}
location /admin/ {
# 对PUT/DELETE方法需要额外认证
if ($request_method ~ ^(PUT|DELETE)$) {
auth_request /auth;
}
# 其他配置...
}
location = /auth {
internal;
proxy_pass http://auth_server;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-Method $request_method;
}
以上方法可以根据实际需求组合使用,实现灵活的基于HTTP方法的访问控制策略。