【问题标题】:htaccess rewrite always passes filename instead of actual urlhtaccess rewrite 总是传递文件名而不是实际的 url
【发布时间】:2018-03-26 08:17:14
【问题描述】:

我有以下 .htaccess 文件

RewriteEngine on
RewriteRule ^(.*)/?$ index.php?file=$1 [L]

所以我希望它将 mysite.com/foobar 转发到 mysite.com/index.php?file=foobar
我有以下 index.php 文件

<?php
    var_dump($_GET);
?>

无论我调用哪个url(mysite.com、mysite.com/foobar、mysite.com/test),index.php的输出总是

array(1) { ["file"]=> string(9) "index.php" }

而我期待一个

array(1) { ["file"]=> string(0) "" }
array(1) { ["file"]=> string(6) "foobar" }
array(1) { ["file"]=> string(4) "test" }

$_SERVER['QUERY_STRING'] 也返回“file=index.php”

我认为不涉及任何其他 htaccess 文件,当我将随机字符写入 .htaccess 文件时,我会收到内部服务器错误(如预期的那样),如果我更改参数“文件”的名称或更改将文件“index.php”的名称改为“test.php”问题保持不变(显示 test.php 而不是 index.php)

【问题讨论】:

    标签: php .htaccess redirect mod-rewrite


    【解决方案1】:

    您遗漏了一些内容。 试试看:
    匹配所有字符:

    RewriteRule ^/?([.*])$ \index.php?file=$1 [L]
    

    如果只需要匹配字母字符:

    RewriteRule ^/?([a-z]+)$ \index.php?file=$1 [L]
    

    如果您想让您的生活更轻松,请使用:http://www.generateit.net/mod-rewrite/index.php 或者,如果您想了解更多关于正则表达式的信息:https://www.princeton.edu/~mlovett/reference/Regular-Expressions.pdf

    【讨论】:

    • 此代码在我调用 mysite.com 或 mysite.com/index.php 时显示 array(0) { },但对于 mysite.com/foobar 之类的调用返回 404 未找到
    • 第一条规则仍然会导致相同的错误 404,但第二条对于我的目的来说工作得很好。谢谢。
    猜你喜欢
    • 2012-06-08
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2011-07-25
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多