我有一个如下所示的 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/