我正在尝试重写 /example-friend-url
以显示 /posts.php?id=1
的内容。
友好的 url 值和 id 都存储在 mysql 表中。
这是我到目前为止所写的内容,但有些地方不对:
posts.php:
include('/functions.php');
$post = getPost($_GET['id']);
$param = getSlug($_GET['param']);
函数.php:
function getPost($id) {
$id = (int) $id;
$query = mysql_query("SELECT * FROM list WHERE id = '$id'") or die(mysql_error());
return mysql_fetch_assoc($query);
}
function getSlug($param) {
$query = mysql_query("SELECT id FROM list WHERE slug = '$param'") or die(mysql_error());
return mysql_fetch_assoc($query);
}
.htaccess:
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/posts.php
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/posts.php?param=$1 [NC,L]
任何帮助将不胜感激。
最佳答案
在 htaccess 文件中处理 mod_rewrite 规则时,前导斜杠将被删除,因此您不需要在正则表达式前面添加 ^/
:
RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/posts.php?param=$1 [NC,L]
您正在将“slug”作为 _GET['param']
传递。没有“身份”。您需要在 posts.php
中将该 slug 转换为 ID:
include('/functions.php');
$post_id = getSlug($_GET['param']);
$post = getPost($post_id);
当然,请确保使用类似 mysql_real_escape_string 的内容对 $_GET['param']
进行清理。 (已弃用,您确实想使用 mysqli )。
关于php - htaccess - 使用 php 和 mysql 重写 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558209/