且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP SEO友好的URL

更新时间:2022-11-26 13:15:55

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

与mod_rewrite的。htaccess的路线

添加在根文件夹,名为.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:

PHP的路线

放入你的.htaccess以下改为:

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,配置和数据库相关的网址等。对于零星的使用在.htaccess硬codeD重写规则会做得很好,虽然

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.

*****复制从 URL与PHP 重写该内容**

*****Copy this content from URL rewriting with PHP**