htaccess url 重写漂亮的 url 在 Apache localhost 上不起作用



我正在尝试将"漂亮"的URL应用于我的网站。

即:localhost/api/?id=15

localhost/api/id/15

这是我的访问:

RewriteEngine On
RewriteBase /api/
RewriteRule ^/?id/([^/d]+)/?$ index.php?id=$1 [L,QSA]

似乎没有任何工作,但htaccess在这里看起来不错。

我需要更新任何 apache 配置吗?

这个htaccess看起来不错。 未启用 htaccess 覆盖和 Apache 重写模块。 我不得不/etc/apache2/apache2.conf编辑文件:

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

并将其更改为;

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

然后

sudo a2enmod rewrite

启用 Apache 重写模块 。

最后使用 sudoservice apache2 restart重新启动 Apache 以查看操作中的更改。

正如评论中@Abhishek提到的,您可以使用AltoRouter。如果轮子存在并且运行良好,那么重新发明轮子是没有意义的。

require 'AltoRouter.php';
$r = new AltoRouter();
$r->map('/api/id/[i:id]', function($userid) {
// your logic for what this URL does
// [i:id] will look for any integers and store it as $userid
}, 'example');
$m = $r->match();
if($m && is_callable($m['target'])):
call_user_func_array($m['target'], $m['params']);
else:
header('Location: /404');
exit();

您可以在网站上找到文档和示例 htaccess。

对于这样的网址

localhost/api/id/15

HTaccess可以像这样

RewriteEngine On
RewriteBase /api/
RewriteRule ^id/([0-9]+)$ index.php?id=$1 [L,QSA]

id=$1你会得到id=15

最新更新