php - 将动态 URL 转换为类似 url 的目录

标签 php apache mod-rewrite

的。我找到了很多关于转换特定 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/

相关文章:

php - 是否可以选择使用我的模板 (PhpStorm) 从源 PHP 类生成测试方法

php - Symfony2 从安全 token 访问用户实体自定义存储库

apache - 拒绝用户使用 .htaccess 访问 php.ini 文件

.htaccess - 删除 .HTACCESS 文件中的所有扩展名

php - 如何在 Zend 框架中使用 mod_rewrite?

angularjs - browserSync 的 modRewrite 不适用于带有 gulp 的路径 'app/index.html' 的 angularjs html5mode

PHP PDO 登录脚本不起作用。包含错误

java - 如何使用Android Studio 0.8.9配置Andengine,Andengine Tiled Map,Physics2DBox?

php - 大流量下的网站PHP+MySQL

python - 名称重复以前的 WSGI 守护进程定义