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

Viewed 10602

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?

4 Answers

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'];

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

Related