简体   繁体   中英

How to rewrite rules NginX in this example?

I am creating an API to feed some apps.

So the app could call these possible URLs to get information from the database;

mysite.com/api/v1/get/menus/list_tblname1.json.php
mysite.com/api/v1/get/menus/list_tblname1.json.php?type=arr
mysite.com/api/v1/get/menus/list_tblname2.json.php
mysite.com/api/v1/get/menus/list_tblname2.json.php?type=arr

In php I have already the code that grabs the tblname from the URL and give me back all the table content. It works good (it is not the final version). But now I find myself copying and pasting the same code for each page where the URL points to. Here is the code:

<?php
header('Content-Type:application/json');
include_once '../../../../class/db.php';
$verb=$_SERVER['REQUEST_METHOD'];

$filePath=$_SERVER['SCRIPT_NAME'];
$split1 = explode("/", $filePath);

preg_match("/(?<=_)[^.]+/", $split1[5], $matches);
$tableName = $matches[0];

if ($verb=="GET") {

        header("HTTP/1.1 200 ok");

        if(isset($_GET['type']) && $_GET['type']=="arr"){
            echo db::get_list($tableName,'arr');//Reply ARRAY  
        }
        else{
            echo db::get_list($tableName);//Reply JSON  
        }
}
else{
        die("Nothing for you at this page!");        
    }

I mean, I have the same code inside each these pages.

list_tblname1.json.php
list_tblname2.json.php

I am not sure how to solve this situation but I think that this is case for rewrite rules.

So, I think a possible solution is to create one page that could call returncontent.php for example and create rules in the server that should point to the same page when certanlly pages are requested and pass the parameter $tableName to the page. I think I should pass the regex to my server and grab the $tableName with $_GET[] (I think) inside returncontent.php .

I am not sure about it.

I am using NginX.

How to implement it in this scenario?

As a rule, it's bad practice to parse a URI in NginX and pass the result downstream.

Rather: mysite.com/api/v1/get/menus/returncontent.php?file=list_tblname2.json

No changes to NginX needed. Parse the query param ( file ) in PHP.

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