htaccess多个重写规则多个子文件夹

时间:2019-01-28 18:25:00

标签: php .htaccess

我很难理解htaccess的工作方式。

这是文件夹结构(近似示例)

# DocumentRoot
# |-- main
# |   |-- site
# |   |   |-- assets
# |   |   |   |-- test.js
# |   |   |-- index.php
# |   |
# |   |-- common
# |   |   |-- assets
# |   |   |   |-- test.js
# |   |
# |   |-- .htaccess

这些是我希望实现的示例重定向

# http://www.example.com/main/assets/test.js            => /main/site/assets/test.js
# http://www.example.com/main/common/assets/test.js     => /main/common/assets/test.js
# http://www.example.com/main/common/path/to/file       => /main/common/path/to/file
# http://www.example.com/main                           => /main/site/index.php
# http://www.example.com/main/part/url                  => /main/site/index.php

我对htaccess文件的尝试如下:

Options -Indexes
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^assets/(.*)$ site/assets/$1 [L]
RewriteRule ^common/(.*)$ common/$1 [L]
RewriteRule ^(.*)$ site/index.php [L]

我的问题: 每个网址都会路由到index.php。我了解错了什么?

当前,所有查询和部分url的处理都在php中进行。我只需要提供两个资产文件夹和其他任何URL中的资源即可转到index.php。

很抱歉,如果这看起来像是我想每天捡鱼,但学会钓鱼,即尝试使我无处可寻。

预先感谢所有帮助。

1 个答案:

答案 0 :(得分:0)

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^assets/(.*)$ site/assets/$1 [L]
RewriteRule ^common/(.*)$ common/$1 [L]
RewriteRule ^(.*)$ site/index.php [L]

RewriteCond伪指令仅适用于其后的第一个RewriteRule。因此,第二两个RewriteRule指令将无条件执行 (这就是为什么所有内容都将被重写为site/index.php的原因)。

我不确定RewriteRule ^common/(.*)$ common/$1 [L]打算做什么-看起来像是潜在的重写循环。

这两个条件检查请求是否映射到文件或目录-这似乎与您要执行的操作相反。从您的文件夹结构/main/assets/test.js 映射到现有文件,因此需要重写。

请尝试以下操作:

 # If a request maps to a file or directory (but not the root directory) then stop
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule . - [L]

 # Any assets (that don't exist) are rewritten to the /site/assets/ subdir
 RewriteRule ^(assets/.*) site/$1 [L]

 # Everything else is rewritten to the site/index.php file
 RewriteRule ^ site/index.php [L]
  

这些是我希望实现的示例重定向

请注意,这些通常称为内部“重写”,而不是严格意义上的“重定向”。 “重定向”表示外部重定向(即3xx响应)。尽管Apache文档在这方面有点模棱两可,但在声明时,它们确实将它们量化为“ 内部重定向”。

相关问题