【问题标题】:Creating A blog with PHP from scratch using htaccess [closed]使用 htaccess 从头开始​​使用 PHP 创建博客 [关闭]
【发布时间】:2015-07-06 22:14:26
【问题描述】:

在不使用任何 PHP 框架的情况下从头开始创建博客,该博客将在我的域根目录中创建一个文件夹,如下所示 domain.com/blog

我怎样才能制作一个 htaccess 文件,让我的博客帖子采用这样的链接:

domain.com/blog/blog-post-test-link-foo-bar

而不是这种方式:

domain.com/blog/post.php?id=1

另外,在我的 post.php 文件中,我想选择该帖子的数据,类似于 url 中的 Slug

我怎么能以纯 php 的方式做到这一点?

【问题讨论】:

  • 这可能更像是一个服务器故障问题。
  • @OIS 这不是服务器故障问题。似乎这与.htaccess 无关。如果您是从头开始创建博客,为什么不将 id 与路径一起存储在数据库中呢?很多开源项目都是这样做的,也许会用到它们。
  • @hoss 他想写一个 RewriteRule。他希望我们为他编写他的 PHP 代码。
  • 甚至重写器都无法处理这个问题,它无法知道什么 id 链接到 foo-bar。但是,是的,我同意。这个问题不是问题。

标签: php .htaccess


【解决方案1】:

您必须创建 /blog/ 文件夹,并在其中放置一个 .htaccess 文件,如下所示:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . ./index.php [L]
</IfModule>

然后在你的 index.php 中你会写如下内容:

<?php
$base = '/blog/';
$uri = $_SERVER['REQUEST_URI'];
$slug = substr($uri, strlen($base));

// Identify the ID of the post
// You identify the ID by searching your posts database on a field like "slug"
// But for now we'll just load from an array
$posts = array(
    'blog-post-test-link-foo-bar' => 1
);
$postId = isset($posts[$slug]) ? $posts[$slug] : null;

if (!is_null($postId)) {
    // Load the post from the database, 
    // or use it if you already loaded it together with the ID
    echo "Loading!";
} else {
    echo "Invalid post!";
}

【讨论】:

    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2012-12-20
    相关资源
    最近更新 更多