How do I Rewrite URLs based on Request Method Using .htaccess?

You can rewrite URLs based on the request method in .htaccess by using the %{REQUEST_METHOD} server variable within a RewriteCond directive. This allows you to apply different routing rules for GET, POST, or any other HTTP method.

The Core Syntax

The general pattern is to check the request method before applying a RewriteRule:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^POST$ [NC]
RewriteRule ^old-path$ /new-path [L]

RewriteCond %{REQUEST_METHOD}: This checks the HTTP method of the incoming request. You can match a specific method like POST, GET, or even use negation like !POST to match everything except POST.
[NC]: This flag makes the match case-insensitive, which is a safe practice for method names.
RewriteRule: This rule is only executed if the condition above it is true.

Practical Examples

1. Separate Rules for GET and POST.

If you need different endpoints for different methods on the same URL, you can stack conditions:

RewriteEngine On

# Route GET requests to one place
RewriteCond %{REQUEST_METHOD} ^GET$
RewriteRule ^api/data$ /handlers/get-data.php [L]

# Route POST requests to another
RewriteCond %{REQUEST_METHOD} ^POST$
RewriteRule ^api/data$ /handlers/post-data.php [L]

This is a common pattern for building simple RESTful routing without a full framework.

2. Blocking a Specific Method.

You can use a negated condition to prevent a method from accessing a resource. For example, to disallow POST to a static file path:

RewriteCond %{REQUEST_METHOD} ^POST$
RewriteRule ^assets/ - [F,L]

The [F] flag returns a 403 Forbidden status, effectively blocking the request.

7 Views