通过.htaccess和PHP美化API的URL [英] Beautify the URL for API by .htaccess and PHP

查看:111
本文介绍了通过.htaccess和PHP美化API的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


考虑到我正在请求此URL进行JSON api响应.


Consider that I am requesting this url for a JSON api response.

// url that user will type in the browser address bar   
example.com/api/user/0001

我有2个选项:


选项A

重定向将像这样.但是浏览器中的地址将与以前相同.

I have 2 Options:


Option A

The redirection will be like this. But The address in the browser will be the same like before.

example.com?get1=api&get2=user&get3=0001

?get1=xxxxxx&get2=xxxxxx,并且很重要.如果网址中有更多的斜杠(/),则会添加更多的GET请求,例如&get4=xxxxx &get5=xxxxx,依此类推.

The ?get1=xxxxxx and &get2=xxxxxx and is IMPORTANT. if there is more slashes (/) in the url it will add more GET request like this&get4=xxxxx &get5=xxxxx and so on.

然后,我将像这样从$_GET['reques']方法获取确切的信息!

Then I will get the exact information form the $_GET['reques'] method like this!

$var_request = $_GET['get1'];
$var_type    = $_GET['get2'];
$var_id      = $_GET['get3'];



选项B

重定向将像这样.但是浏览器中的地址将与以前相同.



Option B

The redirection will be like this. But The address in the browser will be the same like before.

example.com?request=api/user/0001

然后我将这样分解api/user/0001来获得确切的信息

Then I will get the exact information by exploding the api/user/0001 like this

// Geting request by $_GET
$request = $_GET['request'];

// Exploding by the (/)
$api = explode("/", $request);

// Getting my desired information
$var_request = $api[0];
$var_type    = $api[1];
$var_id      = $api[2];





记住:URL与以前相同.它看起来不应该像?get=这样.该网址在浏览器网址栏中仍应为example.com/api/user/0001.

Remember: The URL will be same as before. It should not look like ?get= this. The url should be still example.com/api/user/0001 in the browser url bar.

推荐答案

我认为选项B 会更容易实现.可能的解决方案是-

I think Option B will be easier to do this. Possible solution is-

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+)$ ?request=$1 [L]

它重定向-example.com/api/user/0001example.com?request=api/user/0001,而无需更改浏览器中网址栏中的地址.

It redirects - example.com/api/user/0001 to example.com?request=api/user/0001 Without changing the address in the url bar in you browser.

这篇关于通过.htaccess和PHP美化API的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆