Home > Backend Development > PHP Tutorial > How Can I Rewrite URLs with GET Parameters Using .htaccess?

How Can I Rewrite URLs with GET Parameters Using .htaccess?

DDD
Release: 2024-11-16 13:35:02
Original
950 people have browsed it

How Can I Rewrite URLs with GET Parameters Using .htaccess?

Rewriting GET Variables with .htaccess

Many web applications utilize a URL structure that includes dynamic content, such as the example provided: index.php?page=controller. To improve user experience and maintain a cleaner URL structure, it is desirable to rewrite these URLs to appear in a more user-friendly format. This can be achieved using .htaccess rules.

The provided .htaccess rules effectively rewrite URLs of the form http://localhost/index.php?page=controller to http://localhost/controller/. However, the requirement is to also support GET parameters, resulting in URLs such as http://localhost/controller/param/value/param/value.

To accomplish this, the following RewriteRule can be added to the .htaccess file:

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

This rule captures the entire URL, including any parameters, and assigns the captured data to the params GET variable. Consequently, the URL http://localhost/controller/param/value/param/value would be rewritten to index.php?params=param/value/param/value.

In the PHP script, the params GET variable can be exploded to extract individual parameters and their values. For instance:

<?php

$params = explode("/", $_GET['params']);
for($i = 0; $i < count($params); $i+=2) {

  echo $params[$i] ." has value: ". $params[$i+1] ."<br />";

}

?>
Copy after login

With this modification, the .htaccess rules will successfully rewrite URLs with GET parameters, enabling the PHP script to access these parameters for further processing and controller logic.

The above is the detailed content of How Can I Rewrite URLs with GET Parameters Using .htaccess?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template