我在同一目录中有两个 php 文件 posts.php
和 postdetails.php
。 posts.php
页面列出所有帖子,postdetails.php
在 postid
设置如下时显示帖子:postdetails.php? id=3
我想让 posts
和 postdetails
页面在没有 .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/