At the moment I have a PHP MVC project that needs to have URL rewriting for better usability. However, the project can be installed in different directories and I am unable to write a proper working .htaccess that can handle both cases:
As you can see, I have to different base URIs. The project structure looks like this:
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 (Trial and error...):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [NC,L]
So the idea is that REQUEST_URI should have the following values:
(empty) (System will use the fallback controller)
mycontroller
mycontroller/action
mycontroller/action/42
Question:
In the end I really gave up the possibility to rewrite from two different directories aka two different base URIs. I just added a virtual host to my local system (www.test.com). For interested people, the .htaccess looks like this:
# 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]
Note: The input source of additional files like js, css, images etc. needs to be absolute:
<link href="/public/css/style.css" rel="stylesheet">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.