How can I create user-friendly URLs using .htaccess?

Mary-Kate Olsen
Release: 2024-11-06 12:03:02
Original
694 people have browsed it

How can I create user-friendly URLs using .htaccess?

Creating Pretty URLs with .htaccess

Question: How can I transform URLs with multiple parameters into clean, readable formats using .htaccess?

Answer:

To create pretty URLs with .htaccess, you can utilize rewrite rules. Here's how:

  1. Rewrite Rule for Single Parameter:
    To transform URLs like http://localhost/index.php?user=1 into http://localhost/user/1 using .htaccess, you can implement the following:

    <code class="htaccess">Options +FollowSymLinks
    RewriteEngine On
    
    RewriteRule ^user/(.*)$ ./index.php?user=</code>
    Copy after login
  2. Rewrite Rule for Multiple Parameters:
    To convert URLs like http://www.yourwebsite.com/index.php?user=1&action=update into http://www.yourwebsite.com/user/1/update:

    <code class="htaccess">Options +FollowSymLinks
    RewriteEngine On
    
    RewriteRule ^user/([0-9]*)/([a-z]*)$ ./index.php?user=&action=</code>
    Copy after login
    • Parentheses enclose groups for later retrieval using $1, $2, etc.
    • [0-9]* captures any numbers.
    • [a-z]* captures any characters.
  3. Accessing Parameters in PHP:

    In PHP, you can retrieve the captured parameters:

    <code class="php"><?php 
    echo "user id:" . $_GET['user'];
    echo "<br>action:" . $_GET['action'];
    ?></code>
    Copy after login
  4. Additional Considerations:

    • (.*) can accept almost anything, making it less secure than specific regular expressions like [0-9]*.
    • Groups allow for a more organized and controlled rewrite process.

The above is the detailed content of How can I create user-friendly URLs using .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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!