.htaccess - 子文件夹中的重写规则
问题描述
我有个问题。
有一个自定义的 mvc 结构,当它是根文件夹时,一切都通过 .htaccess 中的 RewriteRule 工作,但如果我将它设置为子文件夹,它就会停止工作。
.htaccess 是
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
AddDefaultCharset UTF-8
然后我改变了基础并添加了:
RewriteBase /mysubfolder/mySubSubfolder/
Cong 文件:
ServerAdmin root@domain.com
DocumentRoot /var/www/rootfolder/
< Directory /var/www/rootfolder >
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
Order allow,deny
allow from all
< /Directory >
< Directory /var /www/rootfolder/sub/sub/ >
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
Order allow,deny
allow from all
< /Directory >
我用重写规则尝试了一些魔术,但似乎我缺乏知识。如果你能帮忙就好了。
谢谢,对不起,我有点菜鸟:)
解决方案
tldr;
假设 .htaccess 文件没有移动到 MVC 应用程序的子目录...
更新全局重定向行:
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
至:
RewriteRule ^(.*)$ subdir/index.php?route=$1 [L,QSA]
对于大多数(如果不是 PHP 中的所有现代 MVC 框架),“所有”非文件路径(URL)都被设计为重定向到“index.php”文件。你可能会注意到这一行:
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
它的设计本质上是采用常规 URL,例如http://example.com/some/path并将其重定向到http://example.com/index.php?route=some/path
它前面的 2 行声明:“如果 URL 不是对文件的请求”
RewriteCond %{REQUEST_FILENAME} !-f
“如果 URL”不是对目录的请求”
RewriteCond %{REQUEST_FILENAME} !-d
然后重定向与正则表达式匹配的任何内容:^(.*)$ 并将其重定向到目标路径
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
我假设您移动了项目(但不是 .htaccess 文件)。
假设上述情况,如果您将项目移动到子目录中,则需要更新目标路径,以使 index.php 路径正确。
例如
RewriteRule ^(.*)$ subdir/index.php?route=$1 [L,QSA]
--
给出正则表达式的速成分解:
^ indicates the string must start with the string provided, e.g. ^apple would mean the string would only match if it starts with the word apple
$ indicates the string must end with the string provided, e.g. banana$ would mean the string would only match if it ended with the word banana
. indicates any character
* following the "." means any number of characters (1 to infinity, theoretically)
简而言之,^(.*)$ 意味着几乎匹配所有内容!
推荐阅读
- python - 从字符串列表中选择合适的选项
- r - Two data frames comparison, how to add ID from one df to the 2nd one but based on condition and range
- java - 使用 Java 在普通 TCP 客户端和 Netty 服务器之间交换 Protobuf 消息
- c++ - 如何获得变量 b 比 a 少 1 的数量?
- function - 外部 OnTap/OnPressed 传递数据 (Flutter)
- python - 问题()名称错误:名称“问题”未定义
- php - Revive Ad 无法升级
- c# - if else条件在Regex c#中并返回常量值
- jenkins - 如何仅在 Jenkinsfile 的声明性管道中有条件地运行 post -> failure 元素?
- python - 如果未找到数据框列,则替换列值