的。我找到了很多关于转换特定 url 字符串的资源(domain.com/?hello=world 到 domain.com/hello/world )但我正在寻找的是一种动态转换我传递给目录结构的任何 url 的方法,或者我应该说,如果你去 domain.com/hello/world 那么它会自动传递到我的 php 脚本:domain.com/?hello/world。我需要它是完全动态的,这样我发送的任何内容都会被转换。
即
domain.com/login/register 被我的 php 脚本视为 domain.com/?login=register domain.com/login = domain.com/?login= domain.com/hello/world = domain.com/?hello=world domain.com/pages/about = domain.com/?pages=about domain.com/about = domain.com/?about
更重要的是,我需要能够做到这一点..
domain.com/login/register/confirm/6473440367233483730126345 = domain.com/?login=register&confirm=6473440367233483730126345 domain.com/posts/categories/general = domain.com/?posts=categories&general
基本上每个奇数目录都是获取键,每个偶数是一个值(如果存在的话)。这需要根据需要持续进行,而不仅限于 2 或 3 个键/值字符串。
编辑:这是我最初想出的(最终解决方案见下文)。
.htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
索引.php
$ReqURI = array_filter(explode('/',$_SERVER['REQUEST_URI']));
这是最终的解决方案,这要归功于这里的几个线程和一些调整。
.htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
索引.php
if(preg_match_all('([^/]+)', $_SERVER['REQUEST_URI'], $matches)){
$val = array();
$key = array();
foreach ($matches[0] as $i => $req){
if($i % 2){
$val[] = $req;
}else{
$key[] = $req;
}
}
if(count($val) < count($key)){
$val[] = '';
}
$params = array_combine($key,$val);
print_r($params);
}
最佳答案
使用上面的 Nev Stokes
的 PHP 代码并尝试像这样创建 .htaccess 文件,这样它就不会破坏其他(静态)资源:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR] # 1. is this a request to static file ?
RewriteCond %{REQUEST_FILENAME} -l [OR] # 2. if not, is it a request to a symlink ?
RewriteCond %{REQUEST_FILENAME} -d # 3. if not, is it a request to a directory ?
RewriteRule ^.*$ - [NC,L] # 4. if true ( any of those three above ), serve the request normally and STOP ( because of L `last` flag ).
RewriteRule ^.*$ index.php [NC,L] # 5. if neither 1,2,3 are true, redirect to index.php
关于php - 将动态 URL 转换为类似 url 的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6170003/