Home >Backend Development >PHP Tutorial >How can I use .htaccess to create pretty URLs from query parameters?

How can I use .htaccess to create pretty URLs from query parameters?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 14:46:02675browse

How can I use .htaccess to create pretty URLs from query parameters?

Creating Pretty URLs with .htaccess

Question: How can I transform a URL from http://localhost/index.php?user=1&action=update to http://localhost/user/1/update using .htaccess?

Answer:

To achieve this transformation, you can use the following .htaccess rules:

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^user/([0-9]*)/([a-z]*)$ ./index.php?user=&action=

Explanation:

  1. Rewrite Groups: The parentheses within the RewriteRule group the user id ([0-9]*) and action ([a-z]*).
  2. Pattern Matching: The pattern ^user/([0-9]*)/([a-z]*)$ matches URLs like user/1/update.
  3. Replacement String: The ./index.php?user=$1&action=$2 specifies that the extracted user id ($1) and action ($2) should be passed as query parameters to index.php.

To Access Parameters in PHP:

To access the extracted parameters in your PHP code, use the following:

<code class="php"><?php
echo "user id:" . $_GET['user'];
echo "<br>action:" . $_GET['action'];
?></code>

Note:

  • The [0-9]* and [a-z]* patterns specify that the user id should only contain numbers and the action should only contain lowercase characters, respectively.
  • Grouping and regular expressions allow for more specific and secure URL transformations compared to using (.*), which accepts almost anything.

The above is the detailed content of How can I use .htaccess to create pretty URLs from query parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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