php - 用 PHP 重写 URL

标签 php .htaccess url mod-rewrite url-rewriting

我有一个看起来像的 URL:

url.com/picture.php?id=51

我将如何将该 URL 转换为:
picture.php/Some-text-goes-here/51

我认为 WordPress 也是如此。

如何在 PHP 中制作友好的 URL?

最佳答案

您基本上可以通过两种方式执行此操作:

带有 mod_rewrite 的 .htaccess 路由

添加一个名为 .htaccess 的文件在您的根文件夹中,并添加如下内容:

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

这将告诉 Apache 为这个文件夹启用 mod_rewrite,如果它被询问匹配正则表达式的 URL,它会在内部将其重写为您想要的内容,而最终用户不会看到它。简单但不灵活,因此如果您需要更多功能:

PHP路线

将以下内容放在您的 .htaccess 中:(注意前导斜杠)
FallbackResource /index.php

这将告诉它运行您的 index.php对于它通常无法在您的站点中找到的所有文件。在那里你可以例如:
$path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
$elements = explode('/', $path);                // Split path on slashes
if(empty($elements[0])) {                       // No path elements means home
    ShowHomepage();
} else switch(array_shift($elements))             // Pop off first item and switch
{
    case 'Some-text-goes-here':
        ShowPicture($elements); // passes rest of parameters to internal function
        break;
    case 'more':
        ...
    default:
        header('HTTP/1.1 404 Not Found');
        Show404Error();
}

这就是大型站点和 CMS 系统的做法,因为它在解析 URL、配置和数据库相关 URL 等方面提供了更大的灵活性。对于偶尔使用的硬编码重写规则 .htaccess不过会很好。

关于php - 用 PHP 重写 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64699429/

相关文章:

php - 拉拉维尔 7 : array validation messages with wildcard index

.htaccess 重定向而不更改地址栏

javascript - 在 React Router v4 中表示 URL 查询

javascript - Javascript 文件的相对 URL

css - 仅在 Safari 中出现后台 Url 问题

php - 从字幕文件中删除 "acceleration"

php - Laravel 5.2 - 使用 Auth::check() 在 MIddleware 中不起作用

PHP preg_match : a pattern which satisfies all MySQL field names (including 'table.field' formations)

php - 如何在 .htaccess 中隐藏 .php 扩展名

php - 设置 apache RewriteMap 以从数据库中提取的正确方法是什么? (PHP/APACHE/MySQL)