通过 .htaccess 和 PHP 美化 API 的 URL [英] Beautify the URL for API by .htaccess and PHP
问题描述
考虑到我正在请求此 url 以获取 JSON api 响应.
//用户将在浏览器地址栏中输入的 urlexample.com/api/user/0001
我有两个选项:
选项 A
重定向将是这样的.但是浏览器中的地址会和之前一样.
example.com?get1=api&get2=user&get3=0001
<块引用>
?get1=xxxxxx
和 &get2=xxxxxx
很重要.如果 url 中有更多斜杠 (/),它将添加更多这样的 GET 请求&get4=xxxxx
&get5=xxxxx
等等.
然后我会像这样从 $_GET['reques']
方法中获取确切的信息!
$var_request = $_GET['get1'];$var_type = $_GET['get2'];$var_id = $_GET['get3'];
选项 B
重定向将是这样的.但是浏览器中的地址会和之前一样.
example.com?request=api/user/0001
然后我会通过像这样爆炸api/user/0001
来获得确切的信息
//通过 $_GET 获取请求$request = $_GET['request'];//由 (/) 爆炸$api =explode("/", $request);//获取我想要的信息$var_request = $api[0];$var_type = $api[1];$var_id = $api[2];
请记住:URL 将与以前相同.它不应该看起来像 ?get=
这个.浏览器网址栏中的网址仍应为 example.com/api/user/0001
.
我认为 选项 B 会更容易做到这一点.可能的解决方案是-
RewriteEngine On重写基数/RewriteCond %{REQUEST_FILENAME} !-fRewriteRule (.+)$ ?request=$1 [L]
它重定向 - example.com/api/user/0001
到 example.com?request=api/user/0001
不改变网址栏中的地址您的浏览器.
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
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
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.
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'];
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
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];
Remember: The URL will be same as before. It should not look like
?get=
this. The url should be stillexample.com/api/user/0001
in the browser url bar.
I think Option B will be easier to do this. Possible solution is-
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+)$ ?request=$1 [L]
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屋!