为什么.htaccess文件不重写url中的“-”

vltsax25  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(137)

所以,我有一个网站http://example.com,我有一个数据库的文章和什么没有,当文章ID是http://example.com/article,一切都很好,重写是正确的,但当ID是http://example.com/article-name我得到一个404.
这是代码:
.htaccess

RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)$ index.php?ID=$1
RewriteRule ^c/([^/]+)?$ index.php?CAT=$1 [L,QSA]
RewriteRule ^topic/([^/]+)?$ index.php?topic=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

article.php

<?php
if (isset($_GET['ID'])) {
require_once 'con.php';
$ID = mysqli_real_escape_string($conn, $_GET['ID']);
$sql = "SELECT * FROM `blog_article` WHERE articleID = '$ID' ";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
if (mysqli_num_rows($result) == 0) {
    header("Location: /");
}
else{
    include 'article.php';
}
} 
elseif (isset($_GET['CAT'])) {
      include 'c.php'; 
} 

elseif (isset($_GET['topic'])) { 
    include 't.php'; 
  } 
else {
include 'index_view.php';
}
 ?>
jv2fixgn

jv2fixgn1#

此重写规则:

RewriteRule ^([a-zA-Z0-9]+)$ index.php?ID=$1

意思是“如果你在一个序列中看到一个或多个字母或数字,把它重写为index.php?ID=the_sequence_that_was_found”
该规则不包括任何标点符号,如-。如果您希望它考虑捕获字母、数字和破折号,则该行应改为:

RewriteRule ^([a-zA-Z0-9-]+)$ index.php?ID=$1

注意如果你想在这里添加更多的字符,你可能需要对它们进行转义。这是因为像破折号这样的字符对于这些regex patterns来说是一个特殊的字符,所以反斜杠告诉Apache它应该是一个像这样的文字破折号:

RewriteRule ^([a-zA-Z0-9\-]+)$ index.php?ID=$1

相关问题