【问题标题】:htaccess - mod_rewrite pass virtual directory or file back to index.php as parameter?htaccess - mod_rewrite 将虚拟目录或文件作为参数传回 index.php?
【发布时间】:2015-03-18 05:38:16
【问题描述】:

我正在尝试获取要传递回 index.php 的虚拟目录或文件

例如,我希望 / 之后的所有内容都传递回索引,然后将针对数据库进行检查,但是“virtual_directory”和“virtual_file.jpg”实际上并不存在,它们只是参数。

somedomain.com/virtual_directory
somedomain.com/virtual_file.jpg

现在,问题是 一切 都过去了。因此,假设我只想转到主目录(或只是 index.php),我将输入 url (somedomain.com),它会将尾部斜杠作为参数传递。如果我尝试访问 somedomain.com/index.php 也是一样。它将与 /index.php 一起传递(即:我无法访问 else 语句)。

有没有办法让它在我直接进入索引时不会通过?

这两个将作为参数传递,我也不想要它们。

somedomain.com/
somedomain.com/index.php

.htaccess:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.php [L]

index.php 将读取 '/' 之后的内容并对其进行处理。

if ($_SERVER['REQUEST_URI']) {
    echo nl2br("Parameter Passed!\n");
    echo 'Parameter That Passed:' .$_SERVER['REQUEST_URI'];
} else{
    echo 'No Parameter Passed';
    echo 'You Are Visiting domain.com/ or domain.com/index.php';
}

【问题讨论】:

  • 那么问题出在哪里?
  • 添加了一个问题。我不知何故忘记添加它。

标签: php .htaccess mod-rewrite url-parameters


【解决方案1】:

你的 php 代码的“else”部分没有被访问的原因是因为总会有一个$_SERVER['REQUEST_URI'] 值。这是一个始终是请求的服务器变量。因此,您永远不会遇到“未传递参数”。如果将参数作为 GET 变量或路径信息传递,您可能想要什么:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?request=$1 [L]

你的代码是:

if ($_GET['request']) {
    echo nl2br("Parameter Passed!\n");
    echo 'Parameter That Passed:' .$_GET['request'];
} else{
    echo 'No Parameter Passed';
    echo 'You Are Visiting domain.com/ or domain.com/index.php';
}

或路径信息:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

你的代码是:

if ($_SERVER['PATH_INFO']) {
    echo nl2br("Parameter Passed!\n");
    echo 'Parameter That Passed:' .$_SERVER['PATH_INFO'];
} else{
    echo 'No Parameter Passed';
    echo 'You Are Visiting domain.com/ or domain.com/index.php';
}

【讨论】:

  • 12shadow12的用词很有趣...我只是来写“美丽的答案”。干得好,Jon Lin,非常感谢!
【解决方案2】:

你可以试试这个

 <IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteRule ^(.*)/$ /$1 [L,R=301]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多