使用Amazon EC2,我仍然可以使用Rest.inc.php(REST API),还是有不同的方法?

问题描述:

I'm trying to migrate my REST APIs for a project to Amazon AWS. I have PHP 7.0 installed and working on an EC2 instance. However, I cannot seem to get my API routing working at all. The original version uses Rest.inc.php and .htaccess file. I've set this up on several other servers without any problem, but can't get it working under Amazon AWS.

What I'm wondering is where the problem lies. I'm just getting a not found error on the API calls. Is this likely related to security/signing issues, or should I be using a completely different approach on AWS?

The code I'm using is very similar to the example that seems to popup everywhere you search.

<?php

    require_once("Rest.inc.php");

    class API extends REST {

        public $data = "";

        const DB_USER       = "username";
        const DB_PASSWORD   = "password";

        private $db = NULL;

        public function __construct(){
            parent::__construct();
            $this->dbConnect();
        }

        private function dbConnect(){
            try {
                $this->db = new PDO("mysql:host=myAWShost;dbname=database", self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }

        public function processApi(){

            $func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));

            if((int)method_exists($this,$func) > 0) {
                $this->$func();
            } else {
                $this->response('',404);
            }

        }

        private function activity(){
            ...
        }

        private function appointment(){
            ...
        }

        private function client(){
            ...
        }

        private function facility(){
            ...
        }

        private function person(){  
            ...
        }

        private function personLocation(){
            ...         
        }
    }

    // Initiiate Library

    $api = new API;
    $api->processApi();

?>

.htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ api.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ api.php [QSA,NC,L]   
</IfModule>

For Apache to read the .htaccess file you need to ensure that AllowOverride All is set within your Apache config file, and then restart apache with sudo service httpd restart.

Example:

<Directory "/var/www/html">
AllowOverride None
</Directory>

Becomes:

<Directory "/var/www/html">
AllowOverride All
</Directory>