【发布时间】:2015-02-24 02:32:12
【问题描述】:
我在 htaccess 中使用 Rewrite Rule 来通过 slug 获取页面数据。
我是通过在 .htaccess 中添加行来手动完成的:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !www\.example\.co\.il$ [NC]
RewriteRule ^(.*)$ http://www.example.co.il/$1 [L,R=301]
ErrorDocument 404 /404.php
RewriteRule ^עמוד-מסוים$ /page.php?id=1 [L]
RewriteRule ^דוגמא-לעמוד$ /page.php?id=2 [L]
RewriteRule ^דוגמא-נוספת$ /page.php?id=3 [L]
RewriteRule ^טקסט-כלשהו$ /page.php?id=4 [L]
RewriteRule ^צרו-קשר$ /contact.php [L]
RewriteRule ^blog$ /blog.php [L]
效果很好,但我每次都需要添加新的 .htaccess 行。
我的数据库表有 Id 和 Slug(以及其他信息) 我的 page.php 使用 $_GET['id'] 然后通过这个 ID 从 DB 中选择其他数据。
我尝试过这样的事情:
.htaccess:
RewriteRule ^page/([^/]*)$ /page.php?id=$1 [L]
page.php:
$id=$_GET['id'];
if(is_int($id)==false){ // if slug was enterd
$result=$mysqli->query("SELECT `id` FROM `pages` WHERE `slug`='$id' limit 1");
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
}//query
}
但 URL 看起来不像我想要的(将 /page/ 添加到 url)
我也试过了:
.htaccess:
RewriteRule ^/([^/]*)$ /page.php?id=$1 [L]
但是我网站上的其他 url 有问题(没有连接到 page.php)
如何在不每次都添加 htaccess 行的情况下使其工作?
编辑: 当我尝试这个 .htaccess 时:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !www\.example\.co\.il$ [NC]
RewriteRule ^(.*)$ http://www.example.co.il/$1 [L,R=301]
ErrorDocument 404 /404.php
RewriteRule ^/?([^/]+)$ /page.php?id=$1 [L]
RewriteRule ^צרו-קשר$ /contact.php [L]
RewriteRule ^blog$ /blog.php [L]
我在所有页面上都出现错误,如果我向上移动 RewriteRule ^/?([^/]+)$ /page.php?id=$1 [L] 只有 page.php 文件可以正常工作(博客和联系方式无效),非 WWW 网址也无效。
【问题讨论】:
标签: php .htaccess mod-rewrite redirect slug