如何在像WordPress一样查询帖子时更改查询url模式



我创建了自己的简单帖子管理,我想在像WordPress这样的数据库中查询时更改URL路径。

示例

由此:http://example.com/bob-section/post.php?postlink=how-像理发师一样唱歌

对此:http://example.com/bob-section/how-to-sing-like-barber

这是我目前的.htaccess

#Redirect to non www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}s([^.]+).php [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]
RewriteRule ^index.php$ / [R=301,L]
RewriteRule ^(.*)/index.php$ /$1/ [R=301,L]

您是否考虑过实现路由器?这将允许您将请求URI用作由"/"符号分隔的变量。

我个人更喜欢Aura Router,因为Aura框架允许你只挑选你需要的部分,而不是要求你下载并使用整个框架来实现少数功能。

要开始使用Aura,您可以下载包的git存储库,并包含"bootstrap.php",也可以通过composer包含它。

这是一个快速而肮脏的实现。

.htaccess

RewriteEngine On
RewriteRule ^$ index.php [QSA]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]

index.php

<?php
//This is the file that sets timezones and loads the Aura Router
require(__DIR__ .'/vendor/aura/router/bootstrap.php');
//Create the router
use AuraRouterRouterContainer;
$routerContainer = new RouterContainer();
//This object will let us define routes
$map = $routerContainer->getMap();
/*
* This could be any of the following requests:
*
* $map->get()
* $map->post()
* $map->patch()
* $map->delete()
* $map->options()
* $map->head()
*/
$map->get('post', '/blog/{id}', function ($request, $response) {
$id = (int) $request->getAttribute('id');
$response->body()->write("You asked for blog entry {$id}.");
return $response;
});

以下是路由器功能的一小部分示例:

//Regex validate a url parameter
$map->get('post', '/blog/{id}', function($request, $response) {...})->tokens(['id' => 'd+'])
//Define the same values as in your URL, and you can use the array values to hold your url parameters. This is useful if you have optional parameters, and want to set your default values for routing in your router, rather than in your models
->values(['id' => null])
//Require request on HTTPS port 443
->secure() 
//Set authorization level for a route (very flexible - you could even use bitmasking if you felt up for it)
->auth(['isAdmin' => true])

我将路由划分为子类,并将映射中的参数抽象为单独的数组,然后将数据传递给Aura View库,以获得非常纯的MVC结构。

这是路由器的完整文档。

最新更新