用 PHP 重写 URL [英] URL rewriting with PHP

查看:41
本文介绍了用 PHP 重写 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的网址:

I have a URL that looks like:

url.com/picture.php?id=51

我将如何将该 URL 转换为:

How would I go about converting that URL to:

picture.php/Some-text-goes-here/51

我认为 WordPress 也是如此.

I think WordPress does the same.

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

How do I go about making friendly URLs in PHP?

推荐答案

你基本上可以通过两种方式做到这一点:

You can essentially do this 2 ways:

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

Add a file called .htaccess in your root folder, and add something like this:

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

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

This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

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

Put the following in your .htaccess instead: (note the leading slash)

FallbackResource /index.php

这将告诉它运行您的 index.php 以处理它通常在您的站点中找不到的所有文件.在那里你可以例如:

This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

$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 中的硬编码重写规则将不过做的很好.

This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

这篇关于用 PHP 重写 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆