Home  >  Article  >  Backend Development  >  How to Create Clean URLs with .htaccess?

How to Create Clean URLs with .htaccess?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 22:37:03467browse

How to Create Clean URLs with .htaccess?

Creating Clean URLs with .htaccess

Question:

How can we transform a URL like "http://localhost/index.php?user=1&action=update" into a cleaner version: "http://localhost/user/1/update"?

Answer:

To achieve this, you can modify your .htaccess file with the following code:

Options +FollowSymLinks
RewriteEngine On

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

Here's how it works:

  • Groups: The parentheses in the .htaccess code create groups that can be referenced later using $1, $2, and so on.
  • First Group: It matches any numerical characters (e.g., 1, 34) and captures them in the $1 group.
  • Second Group: It matches any alphabetical characters (e.g., a, abc) and captures them in the $2 group.
  • Replacement String: The replacement string "./index.php?user=$1&action=$2" builds the modified URL using the captured groups $1 and $2.

Accessing Parameters in PHP:

In your PHP code, you can access the URL parameters like this:

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

This approach ensures more control and security compared to using a wildcard character (.*) in the RewriteRule, which could potentially match any string.

The above is the detailed content of How to Create Clean URLs with .htaccess?. 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