简体   繁体   English

在这个例子中如何重写规则NginX?

[英]How to rewrite rules NginX in this example?

I am creating an API to feed some apps. 我正在创建一个API来提供一些应用程序。

So the app could call these possible URLs to get information from the database; 因此,应用程序可以调用这些可能的URL来从数据库中获取信息;

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. 在PHP中,我已经有了从URL中tblname的代码,并将所有表内容返回给我。 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. 但现在我发现自己为URL指向的每个页面复制并粘贴相同的代码。 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. 所以,我认为一个可能的解决方案是创建一个可以调用returncontent.php页面,并在服务器中创建应该在请求certanlly页面时指向同一页面的规则,并将参数$tableName传递给页面。 I think I should pass the regex to my server and grab the $tableName with $_GET[] (I think) inside returncontent.php . 我想我应该将正则表达式传递给我的服务器并使用$ _GET [](我认为)在returncontent.php获取$tableName

I am not sure about it. 我不确定。

I am using NginX. 我正在使用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. 通常,在NginX中解析URI并将结果传递给下游是不好的做法。

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

No changes to NginX needed. 无需更改NginX。 Parse the query param ( file ) in PHP. 在PHP中解析查询参数( file )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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