Home >Backend Development >PHP Tutorial >How Can I Implement URL Rewriting in PHP Using `.htaccess` or PHP's Built-in Functions?
Introduction
URL rewriting is a technique used to transform a complex, potentially lengthy URL into a more user-friendly and readable format. In this article, we'll explore how to implement URL rewriting in PHP using two different approaches: the .htaccess route and the PHP route.
The .htaccess Route with mod_rewrite
This method involves adding a .htaccess file to the root directory and configuring the Apache web server to use mod_rewrite. Here's an example RewriteRule:
RewriteEngine on RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=
This rule instructs the web server that any URL matching the pattern "Some-text-goes-here/
The PHP Route
An alternative approach is to use PHP to handle URL rewriting. This involves setting up a "FallbackResource" in .htaccess:
FallbackResource /index.php
This configuration tells the server to direct all requests to the index.php file if the requested file does not exist. In index.php, you can implement your own URL parsing logic:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); $elements = explode('/', $path); if (empty($elements[0])) { ShowHomepage(); } else { switch (array_shift($elements)) { case 'Some-text-goes-here': ShowPicture($elements); break; case 'more': ... default: header('HTTP/1.1 404 Not Found'); Show404Error(); } }
This technique allows for greater flexibility in URL parsing and support for database-driven and conditional URLs.
The above is the detailed content of How Can I Implement URL Rewriting in PHP Using `.htaccess` or PHP's Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!