我如何使用 .htaccess 在 url 中隐藏我的页面名称?

How i hide my page name in url with .htaccess?

我的代码

RewriteRule ^walls/([0-9a-zA-Z-_]+) display.php?art_nm= [NC,L]

我得到的是:

website.com/walls/i_love_coding

我需要的是:

website.com/i_love_coding

您可能应该使用 front controller pattern。基本上,您将每个请求都交给您的前端控制器,由它决定要做什么。

.htaccess

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

然后,使用您的 "front controller" 转发请求以根据 $_SERVER['REQUEST_URI'] 更正脚本。

index.php

<?php

$name = trim($_SERVER['REQUEST_URI'], '/');
$page = find_page_by_name($name);

if ($page) {
    require $page;
} else {
    require __DIR__.'/errors/404.php';
}

find_page_by_name函数中小心不要return未授权文件的路径;您应该确保您的路径位于特定目录中(请参阅 realpath and strpos)。

例如,攻击者可以尝试获取 http://example.com/../../etc/passwd !!!

对于更复杂的路由,您可能应该尝试像 Silex or Slim 这样的微框架。