Home > Backend Development > PHP Tutorial > How Can I Create User-Friendly URLs with .htaccess and Rewrite Rules?

How Can I Create User-Friendly URLs with .htaccess and Rewrite Rules?

Susan Sarandon
Release: 2024-12-24 12:07:16
Original
382 people have browsed it

How Can I Create User-Friendly URLs with .htaccess and Rewrite Rules?

Creating Friendly URLs with .htaccess

Introduction

Establishing user-friendly URLs is crucial for website usability and search engine optimization. .htaccess offers a versatile tool for achieving this by rewriting URLs into a more aesthetically pleasing and intuitive format. This article addresses a common challenge with .htaccess, namely, converting complex URLs into simpler ones while also incorporating additional parameters based on user input.

The Challenge

The provided sample URL demonstrates the need to convert complex URLs like "http://website.com/index.php?ctrl=pelicula&id=0221889" into more concise and user-friendly versions such as "http://website.com/pelicula/0221889/". Additionally, there is a requirement to include the article title at the end of the URL.

Solution

To craft friendly URLs with .htaccess, we can leverage rewrite rules. Here's a breakdown of how it works:

  1. Enable .htaccess: Start by ensuring that the mod_rewrite module is enabled in your web server configuration.
  2. Rewrite Rules: Create a .htaccess file in the document root directory containing the following rewrite rules:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url= [QSA,L]
Copy after login
  1. PHP Script: In the PHP script, you can access the rewritten URL parameters by manipulating the $_GET['url'] variable. For example:
$path_components = explode('/', $_GET['url']);
$ctrl=$path_components[0];
$id=$path_components[1];
$tab=$path_components[2];
Copy after login

Additional Considerations

  1. **Article

The above is the detailed content of How Can I Create User-Friendly URLs with .htaccess and Rewrite Rules?. 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