Home >Backend Development >PHP Tutorial >How Can I Implement URL Rewriting in PHP Using .htaccess and a PHP-Based Approach?

How Can I Implement URL Rewriting in PHP Using .htaccess and a PHP-Based Approach?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 11:17:10417browse

How Can I Implement URL Rewriting in PHP Using .htaccess and a PHP-Based Approach?

URL Rewriting with PHP

URL rewriting transforms URLs into a more readable and user-friendly format. This guide explores two methods to achieve URL rewriting in PHP: mod_rewrite with .htaccess and a PHP-based approach.

.htaccess Route with mod_rewrite

To use mod_rewrite, create a .htaccess file in the root directory and include the following:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=

This will redirect all URLs matching the regular expression to picture.php, passing the ID as a parameter.

PHP Route

To use PHP, modify the .htaccess file with:

FallbackResource /index.php

In index.php:

$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;
    ...
    default:
        header('HTTP/1.1 404 Not Found');
        Show404Error();
}

This approach gives greater flexibility in handling complex URL structures.

The above is the detailed content of How Can I Implement URL Rewriting in PHP Using .htaccess and a PHP-Based Approach?. 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