将找不到的文件/目录重定向到索引.php同时维护 URL 和查询字符串



我正在使用带有PHP(7.2.27(的apache web(2.4.6(服务器,我正在尝试将所有未找到的目录和文件重定向到指向index.php的域根目录。

因此,当我查询这些 URL 时,例如:https://example.com/file?foo=barhttps://example.com/directory/?foo=bar,我希望它执行我的 PHP 脚本(索引.php(并保留完整的 URL,而不是返回找不到的文件 (404(。我的PHP脚本正在执行重定向过程,因此我需要保持DOCUMENT_URIQUERY_STRING,以$_SERVER

现在我只设法做这个技巧,在我的 PHP 脚本中,我可以处理q参数以获得DOCUMENT_URIQUERY_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"]重写后仅返回目录/文件。

最新更新