简体   繁体   中英

.htaccess changes REQUEST_METHOD to GET - if the URL does not have params or a trailing slash

I'm building an api eg. https://example.com/my-api/api.php

Then I use the following .htaccess file to make the api usable via https://example.com/my-api

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*)$ api.php/$1/ [L,QSA]

The file works, however when my api-call doesn't end with a trailing slash or has some parameters set, the $_SERVER['REQUEST_METHOD'] becomes GET.

Examples:

POST https://example.com/my-api/foo #becomes GET
POST https://example.com/my-api/foo/ #stays POST
POST https://example.com/my-api/foo?bar=1 #stays POST

POST https://example.com/my-api/foo/bar #becomes GET
POST https://example.com/my-api/foo/bar/ #stays POST
POST https://example.com/my-api/foo/bar?abc=1 #stays POST

How could I change this behavior (and is this desirable) or should I inform the users of this api to always end their calls with a trailing slash? When the trailing slash is added, the api works as expected.

I tested this behaviour mostly via PostMan.

It is happening because of a missing slash in your URI which points to a real directory. Apache's mod_dir module adds a trailing slash for those requests and performs a 301 redirect that results in another GET request.

You can disable this behavior but also important to disable option to list directory content for security reasons.

DirectorySlash Off
Options -Indexes

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*)$ api.php/$1/ [L,QSA]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM