.htaccess文件将子目录视为根目录

时间:2014-08-31 05:50:23

标签: apache .htaccess mod-rewrite

我试图允许访问某些资源,例如JS,CSS等,同时默默地将其他所有内容重定向到/index.php,这最终将决定内容的其余部分是否存在。这是为了允许没有所有内容(即静态文件)的友好URL通过PHP。

我正在测试/ public_html / test /目录中的代码,但是一些.htaccess指令需要/ test /而其他不需要。当我让它满意时,我会将它移到/ public_html /目录,但我不想编辑该文件以使其在新位置工作。我所说的是,无论位置如何,我都希望文件以相同的方式工作,而不必对整个路径进行硬编码(因此我可以将其移动到具有不同结构的服务器)。

我在http://localhost/test/中有以下.htaccess文件:

Options -Indexes

RewriteEngine On
RewriteBase /

# Specifically deny /includes/*
RewriteRule ^includes/ - [R=404,L]

# Allow /images/*, /css/* & /js/* but deny everything else, e.g. /lib/*
RewriteCond %{REQUEST_URI} !^/test/images/
RewriteCond %{REQUEST_URI} !^/test/css/
RewriteCond %{REQUEST_URI} !^/test/js/
RewriteRule . - [R=404,L]

我要更改最后一条规则,以便稍后重写为/index.php而不是给出404.目前我只想让.htaccess文件运行得更好。

如何使规则保持一致(即从每个test删除RewriteCond)?我希望能够在/ test /目录中对它进行测试,然后将其移动到Web根目录(即内部/ public_html /),甚至可以将其移动到较低的路径而不更改路径。我尝试过更改RewriteBase,但我并不完全明白它的作用,我也没有看到与其他价值观有任何区别。

如果我将此.htaccess文件移至与/ public_html /?相同的级别,该如何使该文件有效?

理想情况下,我喜欢以下结构:

public_html/
public_html/test/
public_html/test/css/
public_html/test/images/
public_html/test/includes/
public_html/test/js/
public_html/test/lib/
public_html/test/index.php
public_html/.htaccess

如果我把它移到:

那么一切仍然有效
public_html/
public_html/css/
public_html/images/
public_html/includes/
public_html/js/
public_html/lib/
public_html/index.php
.htaccess

1 个答案:

答案 0 :(得分:0)

您可以在规则之前使用动态RewriteBase生成规则:

Options -Indexes

RewriteEngine On

## Determine the RewriteBase automatically/dynamically
RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=BASE:%2]

# Specifically deny /includes/*
RewriteRule ^includes/ - [R=404,L]

# Allow /images/*, /css/* & /js/* but deny everything else, e.g. /lib/*
RewriteCond %{REQUEST_URI} !^%{ENV:BASE}(images|css|js)/ [NC]
RewriteRule . - [R=404,L]