1

我正在尝试使用我在网上找到的教程制作我自己的 MVC PHP 框架。但我在理解 htaccess 文件中的 rewrite_mod 时遇到了问题。这是第一部分:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    public/     [L]
    RewriteRule    (.*) public/$1    [L]
 </IfModule>

1)正如教程中所写,这些规则会将所有请求重定向到公用文件夹,所以第一个问题是为什么我们有两个规则?第一个和第二个是什么意思。一个 2)第二部分是公共文件夹中的另一个 htaccess 文件,其中包含:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

</IfModule>

第二部分将 url 重写为 index.php?url=$1 这部分很清楚,但这部分对我来说有点困难

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

我了解了它,它告诉请求不应该是文件或目录,但 index.php 是文件(在公共目录中)。另一个问题是为什么当我们删除最后一个 .htaccess 文件(在公共目录中)时,我们得到了这个错误:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at admin@127.0.0.1 to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

当我们只有一个只包含这部分的 htacces 时,它工作得好吗?

<IfModule mod_rewrite.c>
RewriteEngine On
</IfModule>

非常感谢 。

4

1 回答 1

2

您可以结合和fix根 .htaccess:

RewriteEngine on
RewriteRule !^public/ public%{REQUEST_URI} [L]

这意味着/public/<uri>如果 REQUEST_URI 不以/public

现在解释一下。

DOCUMENT_ROOT/.htaccess

RewriteRule    ^$    public/     [L]
RewriteRule    (.*) public/$1    [L]
  1. 第一条规则在内部转发到public/,请求 URI 为空,即http://site.com/
  2. 第二条规则是在内部将 URI 转发到public/<URI>

DOCUMENT_ROOT/public/.htaccess

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

在公共目录中:

  1. RewriteCond %{REQUEST_FILENAME} !-f表示如果请求不是针对有效文件
  2. RewriteCond %{REQUEST_FILENAME} !-d表示如果请求不是针对有效目录的
  3. RewriteRule ^(.*)$ index.php?url=$1表示将请求转发到index.php?url=<uri>

参考:Apache mod_rewrite 简介

于 2013-10-19T17:28:53.243 回答