How can I Rewrite GET Variables to Create Clean URLs with .htaccess?

Mary-Kate Olsen
Release: 2024-11-26 19:44:10
Original
871 people have browsed it

How can I Rewrite GET Variables to Create Clean URLs with .htaccess?

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
Copy after login

To:

http://localhost/controller/
Copy after login

You can use the following rewrite rule:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page= [NC]
Copy after login

To handle additional parameters in the URL, you can use the following rewrite rule:

RewriteRule ^(.*)$ index.php?params= [NC, QSA]
Copy after login

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 />";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template