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

How to Create Clean URLs with .htaccess?

Susan Sarandon
Release: 2024-11-05 22:37:03
Original
551 people have browsed it

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

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

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!

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