How to Create a user-friendly URL using .htaccess

March 6, 2023 / How-to Guide

An explanation of creating a user-friendly URL using .htaccess is given in this tutorial. To create a user-friendly URL using “.htaccess”,  you can use the Apache module “mod_rewrite”. This module allows you to modify the URL that is displayed in the browser without actually changing the file path on the server.

Here’s an example of how you can create a user-friendly URL using .htaccess:

  1. Create a file named .htaccess in the root directory of your website if it does not already exist.
  2. Add the following lines of code to the .htaccess file:
    RewriteEngine On
    RewriteRule ^user/([0-9]+)/?$ profile.php?id=$1 [L]

    1. This code will redirect a URL like http://test.com/user/123 to http://test.com/profile.php?id=123.
    2. The RewriteEngine On line tells Apache to enable the mod_rewrite module. The RewriteRule line specifies the pattern to match and the substitution to make.
    3. The pattern ^user/([0-9]+)/?$ matches a URL that starts with /user/ followed by one or more digits, and optionally ends with a trailing slash. The parentheses around ([0-9]+) capture the digits as a group, which can be referred to in the substitution as $1.
    4. The substitution profile.php?id=$1 replaces the matched URL with profile.php?id= followed by the captured digits.
    5. The [L] flag tells Apache to stop processing any further rewrite rules if this rule matches.
  3. Save the .htaccess file and upload it to your website’s root directory.

Now when a user visits a URL like http://test.com/user/123, they will be redirected to http://test.com/profile.php?id=123, but the URL displayed in the browser will remain the user-friendly version.

Our www.webhosting.uk.com support team is available for you around the clock. Check out our most recent web hosting options as well to take advantage of them.

Dominos Search