【问题标题】:Unless I put index.php, I am not recieving the $_GET['url']除非我放 index.php,否则我不会收到 $_GET['url']
【发布时间】:2016-03-27 22:42:00
【问题描述】:

我有一个名为 quick-mvc 的虚拟主机,并且在根目录中有一个 .htaccess 文件。 我已经激活了 mod_rewrite.so。我知道不推荐使用 mod_rewrite,但这是我现在正在使用的,并且希望它能够正常工作。谢谢!

.htaccess 文件

RewriteEngine on

RewriteCond %[REQUEST_FILENAME] !-d
RewriteCond %[REQUEST_FILENAME] !-f
RewriteCond %[REQUEST_FILENAME] !-l

RewriteRule ^(.+)$ index.php?url=$1 [L]

在浏览器前 1

http://quick-mvc/one/two/three/test

$_GET['url'] 返回“index.php”

在浏览器前 2 中

http://quick-mvc/index.php/one/two/three/test

$_GET['url'] 返回“index.php/one/two/three/test”

我想完成什么 即使我像 ex 1 一样添加 index.php,我也想返回 ex 2 显示的内容。我也希望 index.php 不显示。虽然我可以用 php 轻松编写代码。

【问题讨论】:

  • 你应该看看重写模块的文档。尤其是像 REQUEST_URI 这样的变量对您来说很重要,它们可以让您更轻松地访问您感兴趣的实际请求:httpd.apache.org/docs/current/mod/mod_rewrite.html
  • 另一件事:我看不出为什么不推荐重写模块的理由“......确实是这样,如果可能的话,应该避免使用.htaccess 样式文件,因为这些文件是臭名昭著的容易出错,难以调试并且真的会降低服务器的速度。因此,如果您可以访问主机配置,则应该将重写规则放在那里。

标签: php .htaccess mod-rewrite get


【解决方案1】:

您的示例让我想起 Drupal 过去如何将 url 重写到其前端控制器。检查 Drupal 7,他们改变了这样做的方式。

Drupal 7 .htaccess(精简版):

  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

你可以采取类似的方法,然后在 index.php 中:

<?php 
$url = $_SERVER['REQUEST_URI'];
$parts = parse_url($url);

php 函数 parse_url 应该为您提供路径和查询字符串。

$your_url = $parts['path'];

如果放在web根目录下,我们访问这个url:

http://example.com/foo/bar/baz?bat=qux

parse_url 给出:

array
  'path' => string '/foo/bar/baz'
  'query' => string 'bat=qux'

看看其他一些框架,看看它们是如何做到的。

【讨论】:

  • 谢谢。这可能是 arkascha 使用 REQUEST_URI 谈论的内容。我看到这实际上工作得很好。问题仍然存在于是否使用 index.php 上。我可以把 index.php 删掉,但有必要吗?
  • 如果您的规范 url 不包含它,您不需要关心或修剪路径的 index.php。即 url 看起来像 http://example.com/foo/bar 而不是 http://example.com/index.php/foo/bar
猜你喜欢
  • 2014-10-19
  • 2019-11-22
  • 2020-12-04
  • 1970-01-01
  • 2012-12-28
  • 2016-10-15
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多