简体   繁体   中英

PHP: How can I get the URL that has been rewritten with mod_rewrite?

For example, if I rewrite /category/topic/post/ to /index.php?cat=1&topic=2&post=3 , how can I get /index.php?cat=1&topic=2&post=3 using PHP?

You can recreate it pretty easily. $_SERVER['PHP_SELF'] will still give you the correct file name for the script. This should do the trick:

$url = $_SERVER['PHP_SELF'];
$parts = array();
foreach( $_GET as $k=>$v ) {
    $parts[] = "$k=" . urlencode($v);
}

$url .= "?" . implode("&", $parts);

$url will now be the URL you're looking for.

EDIT: @carpereret's answer is far better. Upvote him instead

original uri should be in $_SERVER['REQUEST_URI']

Here is how to get the URL received by PHP after being rewritten with mod_rewrite in Apache:

 $url = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

You can compare this url with the actual url in the browser to debug any rewrite rules in .htaccess

You can set environment variable in mod_rewrite rule and then use it in PHP. Example:

mod_rewrite:

RewriteEngine on
RewriteRule ^/(category)/(topic)/(post)/$ /index.php?cat=$1&topic=$2&post=$3 [L,QSA,E=INDEX_URI:/index.php?cat=$1&topic=$2&post=$3]

PHP:

$index_uri = $_SERVER['INDEX_URI'];

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