.htaccess - .htaccess - 更改网址 - RewriteRule 不起作用
问题描述
我对此很陌生,希望你能帮助我解决这个问题。
我有一个 URL 结构,它从数据库中获取一个 id 并显示如下 url:
www.website.com/post.php?P=18
我想将 URL 呈现为:
www.website.com/post/18
在我的 .htaccess 文件中,我对其进行了如下更改:
RewriteEngine on
RewriteRule ^post/(\w+)$ post.php?P=$1
我已经在 SO 上阅读了一些关于此的帖子,但我似乎无法弄清楚。
我跟着这个:
The Rule:
RewriteRule ^user/(\w+)/?$ user.php?id=$1
Pattern to Match:
^ Beginning of Input
user/ The REQUEST_URI starts with the literal string "user/"
(\w+) Capture any word characters, put in $1
/? Optional trailing slash "/"
$ End of Input
Substitute with:
user.php?id= Literal string to use.
$1 The first (capture) noted above.
谢谢!
解决方案
我认为与可能遇到相同问题的其他人分享此类信息很重要,所以就这样吧。
问题:
[1] 如下所示的链接:www.example.com/news.php?P=1
链接应该看起来像www.example.com/news/1
然后,链接最终必须显示文本而不是 ID。www.example.com/news/news-name
解决方案
首先,我有看起来像这样的锚标签
<a href="news.php?P='.$row['post_id'].'" class="btn btn-link"></a>
它在 URL [1] 中给出了第一个结果。要更改它以使其显示为www.example.com/news/1
,我必须执行以下操作:
创建一个 htaccess 文件并像这样填充它:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC]
### THIS IS AN EXAMPLE FOR MULTIPLE EXPRESSIONS ###
#RewriteRule ^news/([0-9]+)/([0-9a-zA-Z_-]+) news.php?P=$1&name=$2 [NC,L]
RewriteRule ^news/([0-9]+) news.php?P=$1 [NC,L]
然后,将锚标签更改为:<a href="news/'.$row['post_id'].'" class="btn btn-link"></a>
[1] 现在就完成了。
现在的挑战是使用 slug 而不是 ID。在帖子创建页面上,我添加了以下 PHP:
<?php
setlocale(LC_ALL, 'en_US.UTF8');
function slugit($str, $replace=array(), $delimiter='-') {
if ( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
?>
然后,在新闻插入页面上,我添加了: $slug = slugit("$entry1");
,这将 $entry1 = $_POST['title'];
作为页面的标题传递,但是 slugified。在新闻数据库中,我创建了一个列以$slug
作为永久链接名称。
现在要显示带有 slug 的 URL,我必须将锚标记更改为:
<a href="news/'.$row['permalink'].'" class="btn btn-link"></a>
在 htaccess 上,更改RewriteRule ^news/([0-9]+) news.php?P=$1 [NC,L]
为RewriteRule ^news/([0-9a-zA-Z_-]+) news.php?P=$1 [NC,L]
我就是这样让它工作的。我希望这将帮助有类似问题的人解决他们的问题。
推荐阅读
- visual-studio-code - 有没有办法在vscode的查找和替换中禁用ctrl+enter的默认行为?
- javascript - Vue.js - 将模板传递给孙子
- javascript - IE 缩进两个而不是一个
- php - Woocommerce cron 作业 - 单独更改订单的订单状态
- c# - Zip 文件未完全更新
- python - 使用 venv python 为 R 安装 tensorflow?
- java - 清除控制台屏幕以接受来自用户的新值
- javascript - React:尝试在 componentDidMount 之后使用 jquery
- python - 如何更改 LSTM 层的输入尺寸
- swift - GULUserDefaults.m - 109 崩溃