【问题标题】:.htaccess redirect from root( public_html ) to subdirectory and deny direct access to root.htaccess 从根目录(public_html)重定向到子目录并拒绝直接访问根目录
【发布时间】:2018-01-23 15:30:33
【问题描述】:

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]

添加到子目录会和它冲突

【问题讨论】:

  • 不清楚你想要什么。您是要阻止对 app 文件夹的访问,还是要阻止对 subdirectory 以外的任何文件夹的访问?
  • 除了子目录@anubhava之外的任何东西
  • 子目录将包含 index.php、css、js 和 img 任何必须直接访问的内容@anubhava
  • 应该允许example.com/something.php 吗?
  • 不,只有子目录可以直接访问其他内部的东西,比如 PHP @anubhava 的包含和请求

标签: apache .htaccess redirect mod-rewrite


【解决方案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]

【讨论】:

  • 感谢它有效,这RewriteRule ^(.*)$ ?page=$1 [NC] 是否与上述任何@anubhava 冲突
  • 是的,它会发生冲突。该规则的目的是什么?该规则可能应该放在subdirectory/.htaccess
  • 另外,你能解释一下每一行的作用吗@anubhava
  • 是的,它将被添加到那里,但我不知道 .htaccess 是如何工作的@anubhava
  • 你必须写下所有相关的需求。在发布之前我也澄清了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 2017-03-17
  • 2019-07-20
相关资源
最近更新 更多