PHP 如何获取当前重写的 URL,不包括查询字符串


PHP how to get current rewrited URL excluding querystring?

我在.htaccess中使用以下URL重写。

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteRule ^([0-9]+)/([a-zA-Z0-9'&_,-]+)$ business/business_home.php?business_id=$1 [L,QSA]
RewriteRule ^([0-9]+)/([a-zA-Z0-9'&_,-]+)/(about)$ business/business_about.php?business_id=$1 [L,QSA]
RewriteRule ^([0-9]+)/([a-zA-Z0-9'&_,-]+)/(products)$ business/business_products.php?business_id=$1 [L,QSA]
RewriteRule ^([0-9]+)/([a-zA-Z0-9'&_,-]+)/(enquiry)$ business/business_enquiry.php?business_id=$1 [L,QSA]
RewriteRule ^([0-9]+)/([a-zA-Z0-9'&_,-]+)/(contact)$ business/business_contact.php?business_id=$1 [L,QSA]
## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}'s([^.]+)'.php['s'?] [NC]
RewriteRule ^ - [R=404,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]

那么如何获取当前重写的 URL 不包括查询字符串?例如:从具有网址的页面:/22/somestring/enquiry?value=5&page=9&item=coffee我期望:/22/somestring/enquiry

我尝试了$_SERVER['REQUEST_URI']但它返回/22/somestring/enquiry?value=5&page=9&item=coffee而且$_SERVER['REDIRECT_URL']给我我所期望的,但它在某些页面中产生了Notice: Undefined index: REDIRECT_URL。而且它在某些服务器中也不起作用。

在 PHP 中,您可以使用这样的代码来获取没有查询字符串的当前 URI:

$thisuri = preg_replace('/'?.*$/', '', $_SERVER["REQUEST_URI"]);

我不相信 PHP 对没有查询字符串的 URL 有超全局,但您可以手动去除查询字符串:

protected function stripQuery($str){
  return preg_replace('/'?(.*)/', '', $str);
}