.htaccess 将URL重写为PHP内置服务器(XAMPP)中的友好URL

8hhllhi2  于 2023-03-23  发布在  PHP
关注(0)|答案(1)|浏览(144)

我正在创建一个CMS项目,我遇到了一些问题,试图在一个名为PostContainer.php的页面中使URL更友好
我的目标是,当用户访问这个url时:https://localhost/ProjetoCMS/PostContainer. php?slug = post-numero-01-teste-01&id = 1,显示的url是:https://localhost/posts/post-numero-01-teste-01,因为我在PostContainer.php页面中的php代码通过GET获取slug和id,并查询我的数据库以访问正确的结果:我的PostContainer.php文件:

<?php
//database connection
require('./ConexaoSql.php');
//verify if slug an id where sent
if (isset($_GET['slug']) && isset($_GET['id'])) {
    //Select the post from the database
    $id = $_GET['id'];
    $stmt = $pdo->prepare("SELECT * FROM `controle-de-posts` WHERE id = :id");
    $stmt->bindValue(':id', $id);
    $stmt->execute();
    $post = $stmt->fetch(PDO::FETCH_ASSOC);
  
    $url = "/posts/" . $_GET['slug'];
    if ($_SERVER['REQUEST_URI'] !== $url) {
      header("Cache-Control: no-cache, must-revalidate");
      header("Location: $url");
      exit();
    }
  } else {
    header("Location: index.php");
    exit();
  }
  ?>
  
  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="UTF-8">
    <title><?php echo $post['titulo']; ?></title>
    <link rel="stylesheet" href="./CSS/PostContainer.css">
  </head>
  <body>
    <header>
      <?php require_once("./Header.php"); ?>
    </header>
    <div class="corpo-texto">
      <div class="postcontainer-area">
        <!--Title -->
        <h1><?php echo $post['titulo']; ?></h1>

        <!--Post text-->
        <p><?php echo $post['texto_post']; ?></p>
      </div>
    </div>
  </body>
  </html>

但是当文件加载时,它显示“未找到文件”,就像服务器请求此URL一样:“https://localhost/posts/post-numero-01-teste-01”,它不存在,好吧,但我使用.htaccess将所有请求重定向到^posts/([^/]+)/?$到文件PostContainer.php?slug=$1&id=$2
我的.htaccess文件:

RewriteEngine On
RewriteRule ^posts/([^/]+)/?$ /PostContainer?slug=$1&id=$2 [L]

但是仍然显示我没有找到文件。我如何解决这个问题?我如何让用户在访问时看到友好的URL:但是,显示原始URL的内容
我已经试着在网上搜索了很多关于.htaccess的东西,并且已经在apache.conf中启用了rewrite_modules
已启用AllowOverride
已尝试使用测试规则,如:

Rewriterule ^/test example.com.br [NC, L]
8tntrjer

8tntrjer1#

你能试试这个吗:

RewriteEngine On
RewriteRule ^posts/([^/]+)/(\d+)$ /PostContainer?slug=$1&id=$2 [L]

这将重定向任何格式的URL:
https://localhost/posts/post-numero-01-teste-01/1https://localhost/PostContainer?slug=post-numero-01-teste-01&id=1

相关问题