Rewriting GET Variables with .htaccess
In web development, it's often desirable to create clean and aesthetically pleasing URLs while maintaining the functionality of request parameters. This can be achieved using .htaccess rewrite rules.
Suppose you have an index.php file that handles all routing, receiving GET variables as "page" parameters. To achieve the following URL rewrite:
http://localhost/index.php?page=controller
To:
http://localhost/controller/
You can use the following rewrite rule:
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page= [NC]
To handle additional parameters in the URL, you can use the following rewrite rule:
RewriteRule ^(.*)$ index.php?params= [NC, QSA]
With this rewrite rule, your actual PHP file will receive the parameters as "params" in the GET array. You can access the parameters by exploding the "params" string using code like this:
$params = explode("/", $_GET['params']); for($i = 0; $i < count($params); $i+=2) { echo $params[$i] . " has value: " . $params[$i+1] . "<br />"; }
This solution allows you to maintain clean URLs while accessing GET parameters in your PHP script, providing a user-friendly and consistent web experience.
The above is the detailed content of How can I Rewrite GET Variables to Create Clean URLs with .htaccess?. For more information, please follow other related articles on the PHP Chinese website!