首页 > 解决方案 > .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.

谢谢!

标签: .htaccessurlmod-rewritepermalinks

解决方案


我认为与可能遇到相同问题的其他人分享此类信息很重要,所以就这样吧。

问题:

[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]

我就是这样让它工作的。我希望这将帮助有类似问题的人解决他们的问题。


推荐阅读