.htaccess从root(public_html)重定向到子目录并拒绝直接访问root

时间:2017-08-15 16:42:18

标签: apache .htaccess redirect mod-rewrite

M1: 这适用于从根目录重定向到子目录

# .htaccess main domain to subdirectory redirect 
RewriteEngine on 
# Change example.com to be your main domain. 
RewriteCond %{HTTP_HOST} ^(www.)?example.com$ 
# Change 'subdirectory' to be the directory you will use for your main domain. 
RewriteCond %{REQUEST_URI} !^/subdirectory/ 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
# Change 'subdirectory' to be the directory you will use for your main domain. 
RewriteRule ^(.*)$ /subdirectory/$1 
# Change example.com to be your main domain again. 
# Change 'subdirectory' to be the directory you will use for your main domain 
# followed by / then the main file for your site, index.php, index.html, etc. 
RewriteCond %{HTTP_HOST} ^(www.)?example.com$ 
RewriteRule ^(/)?$ subdirectory/index.html

M2: 这可以拒绝直接访问root

根目录中的.htaccess(public_html)

Order deny,allow
Deny from all

然后使用它允许直接访问子目录

.htaccess在子目录

Allow from all

网站结构

public_html
     |___ subdirectory ___ index.php
     |___ .htaccess
     |___ app
     |___ something.php

当我添加它们时,example.com给出了

您无权访问此服务器上的/。

第一次更改.htaccess中的任何内容

修改

我想做的是阻止直接访问除子目录之外的任何内容。

如果

RewriteRule ^(.*)$ ?page=$1 [NC]
如果添加到子目录

将与它发生冲突

1 个答案:

答案 0 :(得分:1)

这样做:

RewriteEngine on 

# for example.com rewrite landing page to subdirectory/index.html
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^/?$ subdirectory/index.html [L]

# for example.com rewrite all other URIs to subdirectory/uri
# (?!subdirectory/) is a negative lookahead that stops rewrite then uri 
# already starts with /subdirectory/
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^(?!subdirectory/)(.+)$ subdirectory/$1 [L,NC]