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 等方面提供了更大的灵 active 。对于零星使用,.htaccess 中的硬编码重写规则将不过做的很好。

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

相关文章:

php - 在同一张表上同时更新和选择

php - 如何在网站的所有其他 PHP 文件中包含一个 PHP 文件?

.htaccess - 只需使用 .htaccess 删除一个 url 段

url - 碧 Jade : error opening input stream from url

jquery - 使用 ERB/jquery 链接到下一页

jquery 检查 URL 是否有查询字符串

php - 添加文本时停止闪烁(清除框并重新填充)的算法

php - 单击“返回”时,客户的 CC 双倍收费

php - 如何在 codeigniter 4 中自动加载辅助函数

.htaccess - 如何删除htaccess中的url参数