.htaccess不包括目录问题

时间:2014-07-22 15:45:31

标签: apache .htaccess mod-rewrite

我有一个由单个index.html文件组成的网站。我有几个菜单,需要深入3级,所以我想要一个类似php的结构:index.html?main=$1&secondary=$2&tertiary=&3。这必须减少到www.example.com/$1/$2/$3。我认为整体非常简单,在.htaccess中使用以下规则:

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)?$  index.html?main=$1&secondary=$2&tertiary=$3
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)?$  index.html?main=$1&secondary=$2
RewriteRule ^([A-Za-z0-9-]+)?$  index.html?main=$1

现在,我的根文件夹中还有几个文件夹不应该受到影响,否则我的包不会工作。查看this answer我已经尝试在其他规则之前使用RewriteRule ^(bower_components|photos)($|/) - [L]排除这些文件夹,但它不起作用。我还尝试了this answer,使用.htaccess进行了RewriteEngine Off并将其放入我的文件夹中,但也没有成功。显然我在某处做错了。为了显示我的文件夹布局,这里是它的快照:

Folder Layout

这是我当前的.htaccess文件:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f  [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .*  - [L]

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)?$  index.html?main=$1&secondary=$2&tertiary=$3
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)?$  index.html?main=$1&secondary=$2
RewriteRule ^([A-Za-z0-9-]+)?$  index.html?main=$1

现在,如果我转到http://localhost/myProject/activities,因此index.html文件位于myProject中1级,它确实有效,所有包含都正确包含在内。但是,当转到http://localhost/myProject/activities/test时,我会转到基本index.html页面,但我的包含指向http://localhost/myProject/activities/bower_components/platform/platform.js,因此activities太多了。

1 个答案:

答案 0 :(得分:1)

保持这样的规则:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /myProject/

RewriteCond %{REQUEST_FILENAME} -f  [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .*  - [L]

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$  index.html?main=$1&secondary=$2&tertiary=$3 [L,QSA]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$  index.html?main=$1&secondary=$2 [L,QSA]
RewriteRule ^([A-Za-z0-9-]+)/?$  index.html?main=$1 [L,QSA]

然后对于css / js / image包含,只需在css,js,images文件中使用绝对路径,而不是相对的路径。这意味着您必须确保这些文件的路径以http://或斜杠/开头。

您还可以尝试在页面的HTML标题中添加此标题:<base href="/myProject/" />,以便从该网址解析每个相对网址,而不是当前网址。