php - 使用 .htaccess 文件创建用户友好的 URL

标签 php .htaccess url-rewriting

我在同一目录中有两个 php 文件 posts.phppostdetails.phpposts.php 页面列出所有帖子,postdetails.phppostid 设置如下时显示帖子:postdetails.php? id=3

我想让 postspostdetails 页面在没有 .php 的情况下也可以访问,并且还添加了一个尾部正斜杠,例如:

代替 www.domain.com/posts.php

我会:

www.domain.com/posts/

我用过这个:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

现在我可以按我想要的方式访问 posts.php,如:www.domain.com/posts/

但现在所有帖子都将链接显示为 www.domain.com/posts/postdetails.php?id=NUMBER

问题是我希望他们也喜欢他们在 posts 子目录中,但我似乎无法让它工作。

我还想将 id 更改为 slug

这样我就有了类似 postdetails.php?slug=this-is-a-post 的东西,并把它适本地重新路由到 www.domain.com/posts/this-是一个帖子/

我正在使用这个函数来创建我的 slug。

function createSlug($str)
{
    if($str !== mb_convert_encoding( mb_convert_encoding($str, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') )
        $str = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    $str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace('`&([a-z]{1,2})(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);`i', '\\1', $str);
    $str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace(array('`[^a-z0-9]`i','`[-]+`'), '-', $str);
    $str = strtolower( trim($str, '-') );
    return $str;
}

有什么帮助吗?

最佳答案

创建一个目录 posts 和一个索引文件(显示一个帖子列表,链接到漂亮的 url)和这个 .htaccess:

RewriteCond %{REQUEST_URI} ^/posts/[^/]+/.*$
RewriteRule ^/posts/([^/]+)/$ postdetails.php?slug=$1 [QSA,L]

漂亮的网址

in this pattern:
http://www.example.com/posts/slug/

e.g.:
http://www.example.com/posts/keywords-are-here/

在文件 postdetails.php 中,您可以评估参数 $_GET['slug']

关于php - 使用 .htaccess 文件创建用户友好的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456312/

相关文章:

php - SELECT DISTINCT 名称但返回所有数据

php - 错误 : incomplete chunked encoding in php scripts

php - 使用 '==' 或 '===' 与 'strcmp()' 进行字符串比较

php - 对用户隐藏 PHP

regex - 当请求旧网址时,有什么方法可以重定向到干净的网址吗?

php - Laravel auth 中间件使用了错误的数据库

apache - mod_rewrite : remove query string from URL?

php - htaccess 将 .htm 和 .php 页面重定向到无扩展名

php - 当url重写阻塞时如何获取更多参数?

url - SEO 被 URL 转发破坏 - 想不出其他方法