[英]How can I use the .htaccess file to rewrite URL's for a subdirectory?
我目前正在使用它来使我的 URL 看起来很漂亮:
ErrorDocument 403 /404.php
ErrorDocument 404 /404.php
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule . index.php [L]
</IfModule>
我终于让它工作了(我对此很陌生),但现在我需要它来为位于主站点子目录中的“子站点”工作。 Instead of rewriting https://example.com/index.php it needs to rewrite https://example.com/sub/index.php
我尝试了一些事情,比如更改 RewriteBase 和 RewriteRule,但没有成功。
可以肯定的是,我应该可以将另一个 .htaccess 放在子目录中,并期望它重写 example.com/sub 的 URL,对吗?
提前致谢!
编辑我向主 .htaccess 添加了例外,如下所示: ErrorDocument 403 /404.php ErrorDocument 404 /404.php Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^(/controle|/controle/|/voting|/voting/.*)$
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule . index.php [L]
</IfModule>
但是,我仍然不知道将什么放入子目录中的 .htaccess 中,同样的一个不起作用,我尝试将RewriteBase /
更改为RewriteBase /subdir1/
可以肯定的是,我应该可以将另一个
.htaccess
放在子目录中,并期望它重写example.com/sub
的 URL,对吗?
是的。 默认情况下,/ .htaccess
/subdir/.htaccess
中的 mod_rewrite 指令。 但是,您将需要重新定义ErrorDocument
指令以覆盖根。
RewriteCond %{REQUEST_FILENAME}/index.html.-f RewriteCond %{REQUEST_FILENAME}/index.php !-f
澄清一下,在这两个条件下,您是否希望偶尔从请求的子目录提供index.html
或index.php
(DirectoryIndex) 文档,而不是将请求路由到文档根目录中的/index.php
? 在这种情况下,简单地检查请求是否不是 map 到目录(即RewriteCond %{REQUEST_FILENAME} !-d
)会更常见(并且稍微更优)。 除非有一些物理子目录要路由到文档根目录中的/index.php
?
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME}.-f RewriteCond %{REQUEST_FILENAME}/index.html.-f RewriteCond %{REQUEST_FILENAME}/index.php !-f RewriteRule . index.php [L] </IfModule>
这些指令可以稍微简化 - 如果您想将相同的指令应用于/subdir
中的子站点(并改为提供/subdir/index.php
),这将对您有所帮助。
完全删除RewriteBase
指令。 相对替代字符串,即。 index.php
,然后将相对于.htaccess
文件所在的目录(或继承)。
您也不需要<IfModule mod_rewrite.c>
包装器。 有关更多信息,请参阅我对 Webmasters Stack 上以下问题的回答: https://webmasters.stackexchange.com/questions/112600/is-checking-for-mod-write-really-necessary
所以,上面可以写成:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule . index.php [L]
(请注意我上面关于用目录检查替换这两个条件的评论。)
现在,您可以简单地将完全相同的指令复制到/subdir/.htaccess
文件中,这些指令现在会将请求路由到/subdir/index.php
,而不是覆盖父项中的 mod_rewrite 指令。
无需复制Options -Indexes
,除非您想更改此选项。
或者,如果您想应用完全相同的指令(但与/subdir
相关),您只需在/subdir/.htaccess
文件中启用 mod_rewrite inheritance 即可。 例如:
# /subdir/.htaccess
ErrorDocument 403 /subdir/404.php
ErrorDocument 404 /subdir/404.php
RewriteEngine On
RewriteOptions Inherit
RewriteOptions Inherit
的作用本质上是从父配置中“复制” mod_rewrite 指令,即。 /.htaccess
在根目录中,位于当前/subdir/.htaccess
文件中的指令后面。 重要的是要澄清指令是“复制的”,它们不像在根/.htaccess
文件中那样就地运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.