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

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

问题描述

我有一个看起来像一个网址:

I have a URL that looks like:

url.com/picture.php?id=51

我怎么会去有关转换网址为:

How would I go about converting that URL to:

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

我觉得字preSS不一样的。

I think WordPress does the same.

我如何去制作友好的URL在PHP?

How do I go about making friendly URLs in PHP?

推荐答案

您基本上可以做到这2种方式:

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的该文件夹,如果它被要求匹配正EX pression它重写它的的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:

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(count($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,配置和数据库相关网址等零星使用硬codeD重写规则的.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重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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