Home >Backend Development >PHP Tutorial >How Can I Create Human-Readable URLs Using .htaccess and Mod_Rewrite?

How Can I Create Human-Readable URLs Using .htaccess and Mod_Rewrite?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 04:11:08784browse

How Can I Create Human-Readable URLs Using .htaccess and Mod_Rewrite?

Customizing Friendly URLs with .htaccess

Creating human-readable URLs is crucial for user experience and search engine optimization. This article provides a detailed guide on customizing friendly URLs using .htaccess, addressing specific requirements and best practices.

To convert URLs from:

  • http://website.com/index.php?ctrl=pelicula&id=0221889
  • http://website.com/index.php?ctrl=pelicula&id=0160399&tab=posters

To:

  • http://website.com/pelicula/0221889/
  • http://website.com/pelicula/0221889/posters/

Follow these steps:

1. Create .htaccess File

In the document root of your website, create a file named ".htaccess".

2. Configure .htaccess

Add the following code to the .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url= [QSA,L]
</IfModule>

3. PHP Script Manipulation

In your PHP script, you can now manipulate the $_GET['url'] variable to extract the desired components. For example:

$path_components = explode('/', $_GET['url']);
$ctrl = $path_components[0];
$id = $path_components[1];
$tab = $path_components[2];

4. Additional Customization

If you want to add the article title to the end of the URL, you can modify the RewriteRule in .htaccess to:

RewriteRule ^(.*)/(.*)$ index.php?url=/ [QSA,L]

5. Error Handling

If you encounter errors after configuring .htaccess, ensure that mod_rewrite is enabled and working. Additionally, review the RewriteCond and RewriteRule directives to ensure they match your requirements.

Best Practices

  • Enable mod_rewrite before adding RewriteEngine On in .htaccess.
  • Use relative paths (e.g., "/index.php") in RewriteRules.
  • Handle 404 errors appropriately.
  • Test and monitor URL changes to avoid any unexpected consequences.

The above is the detailed content of How Can I Create Human-Readable URLs Using .htaccess and Mod_Rewrite?. 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