To configure an Nginx location that only accepts POST requests, you have two primary options: using the limit_except directive or an if block. Both approaches effectively restrict the HTTP methods allowed for a given location.
✅ Recommended Approach: Using limit_except
The limit_except directive is the most idiomatic and efficient way to restrict HTTP methods. It allows you to specify which methods are allowed, and by default, all other methods are denied.
location /post-only {
limit_except POST {
return 405; # Return "Method Not Allowed" for non-POST requests
}
# Other directives for POST requests (e.g., proxy_pass)
proxy_pass http://backend;
}
Explanation:
limit_except POST { ... } tells Nginx to allow only POST requests.
- The block inside
limit_except applies to all other methods (e.g., GET, PUT, DELETE).
return 405; ensures that non-POST requests receive a 405 Method Not Allowed response, which is the correct HTTP status code for this scenario.
🔄 Alternative: Using if Block
If you prefer more control or need to return a custom error message, you can use an if block to check the request method explicitly.
location /post-only {
if ($request_method != POST) {
return 405; # Return "Method Not Allowed" for non-POST requests
}
# Other directives for POST requests (e.g., proxy_pass)
proxy_pass http://backend;
}
Notes:
- The
if block is less efficient and can sometimes cause unexpected behavior due to Nginx's internal processing, but it works fine for this simple case.
- This method is useful if you want to add more logic or custom responses based on the method.
🧠 Key Considerations
- HTTP Status Codes: Use
return 405; for non-POST requests to conform to the HTTP spec.
- Nginx Version:
limit_except is available in Nginx 1.3.12 and later. If using an older version, use the if block.
- Performance:
limit_except is more efficient and avoids potential pitfalls of using if.
✅ Summary
Use limit_except POST { return 405; } for a clean, idiomatic solution. If you need more flexibility or are on an older Nginx version, use the if block. Both ensure only POST requests are accepted for the specified location.