将MVC URL重写到不同的目录


Rewrite MVC URL to different directories

目前我有一个PHP MVC项目,需要重写URL以提高可用性。然而,该项目可以安装在不同的目录中,我无法编写一个正确的工作.htaccess来处理这两种情况:

  1. /var/www/html/testapp/-直接访问:127.0.0.1/testapp
  2. /var/www/html/specific_installation_number_4-虚拟主机:www.testapp4.org

正如您所看到的,我必须使用不同的基本URI。项目结构如下:

testapp/
    index.php
    .htaccess
    public/
        css/
            style.css
        js/
            script.js
    vendor/
        frameworks/
            jquery/
        twitter/
            bootstrap/

index.php:

<?php
echo("GET: ");
var_dump($_GET);
echo("<br>URI: " . $_SERVER["REQUEST_URI"]);
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="vendor/frameworks/jquery/jquery.min.js"></script>
        <script src="vendor/twitter/bootstrap/dist/js/bootstrap.min.js"></script>
        <script src="public/js/script.js"></script>
        <link href="vendor/twitter/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="public/css/style.css" rel="stylesheet">
        <title>Testapp</title>
    </head>
    <body>
        <h1>Testapp</h1>
        <p>Not implemented yet!</p>
    </body>
</html>

.htaccess(试错…):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [NC,L]

因此,REQUEST_URI应该具有以下值:

(empty) (System will use the fallback controller)
mycontroller
mycontroller/action
mycontroller/action/42

问题:

  1. 有人能发布/提示我使用工作版本吗
  2. 有人能解释一下.htaccess中的想法/使用的语法吗

最后,我真的放弃了从两个不同的目录重写的可能性,也就是说,从两个基本URI重写。我刚刚在本地系统(www.test.com)中添加了一个虚拟主机。对于感兴趣的人来说,.htaccess看起来像这样:

# Enable rewriting
RewriteEngine On
# Skip the public and vendor directories
RewriteRule ^(public|vendor)($|/) - [L]
# Skip existing files and directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite the URL
RewriteRule ^(.*)$ index.php [QSA,L]

注意:js、css、image等附加文件的输入源必须是绝对的:

<link href="/public/css/style.css" rel="stylesheet">