我正在使用带有PHP(7.2.27(的apache web(2.4.6(服务器,我正在尝试将所有未找到的目录和文件重定向到指向index.php
的域根目录。
因此,当我查询这些 URL 时,例如:https://example.com/file?foo=bar
或https://example.com/directory/?foo=bar
,我希望它执行我的 PHP 脚本(索引.php(并保留完整的 URL,而不是返回找不到的文件 (404(。我的PHP脚本正在执行重定向过程,因此我需要保持DOCUMENT_URI
和QUERY_STRING
,以$_SERVER
。
现在我只设法做这个技巧,在我的 PHP 脚本中,我可以处理q
参数以获得DOCUMENT_URI
和QUERY_STRING
但它有点丑陋:
<Directory "/var/www/sites/example.com">
DirectoryIndex index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>
该RewriteRule
的示例输出:
- 从这个
https://example.com/file?foo=bar
->https://example.com/index.php?q=file&foo=bar
- 从这个
https://example.com/directory/?foo=bar
->https://example.com/index.php?q=directory/&foo=bar
你有什么想法吗?
多谢
我终于找到了解决这个问题的方法。所以,重写:
<Directory "/var/www/sites/example.com">
DirectoryIndex index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
</Directory>
如何获取初始URL(重写之前(,包括目录/文件和查询字符串:
<?php
$url = $_SERVER["REQUEST_URI"];
// If you want to only get the path without the query string
$url = strtok($_SERVER["REQUEST_URI"], '?');
?>
$_SERVER["REQUEST_URI"]
在重写之前包括查询字符串和目录/文件(例如file?foo=bar...(。其中$_SERVER["DOCUMENT_URI"]
重写后仅返回目录/文件。