2011-12-08 53 views
0

在我的网站上,当有人请求一个目录时,我希望它删除'/'并添加'.html'(当然,减去引号) 。使用htaccess将目录名称重定向到directory-name.html

例:
如果有人去domain.com/directory/它应该重定向到domain.com/directory.html/和同样应该代表:domain.com/another-directory/应该重定向到domain.com/another-directory.html

我想的代码行(或两个)的地方,我htaccess文件,这将使任何目录(URL与/结尾)重定向到URL.html(除去当然/)。

我也希望它在视觉上重定向,所以用户将实际看到它更改为.html

我是一个新手程序员,任何帮助,非常感谢。

注意:我确实使用了Redirect /directory /directory.html,但那样做很有效,但这需要大量额外的编码,而且我更愿意使用一个简单的语句来覆盖所有目录。

+0

只需创建一个名为'directory'文件夹,把'directory.html'到它,文件重命名为'index.html'。 – Gerben

+0

@Gerben谢谢你,但那不是我想要的。我不想拥有一堆index.html文件。我想为我的主页创建一个index.html文件,但是每个目录的索引都有不同的名称。如果我找不到其他解决方案,我会使用你的。 – Jakar

+0

那么'/ directory /'实际上是否存在?或者你在文档根目录下有一个'directory.html'文件,并且想让它看起来像一个目录? –

回答

1

这将是一个有点困难与htaccess的,我想你要做到以下几点:

  1. 如果有人访问的目录不是根(简单http://domain.com/),将其重定向到以.html结尾的目录名称
  2. 获取重定向后,将.html 返回内部重写到该目录,以便apache可以为该目录提供服务。

第一个是简单的:

# check to make sure the request isn't actually for an html file 
RewriteCond %{THE_REQUEST} !^([A-Z]{3,9})\ /(.+)\.html\ HTTP 
# check to make sure the request is for a directory that exists 
RewriteCond %{REQUEST_FILENAME} -d 
# rewrite the directory to 
RewriteRule ^(.+)/$ /$1.html [R] 

第二部分是棘手

# check to make sure the request IS for an html file 
RewriteCond %{THE_REQUEST} ^([A-Z]{3,9})\ /(.+)\.html\ HTTP 
# See if the directory exists if you strip off the .html 
RewriteCond %{DOCUMENT_ROOT}/%2 -d 
# Check for an internal rewrite token that we add 
RewriteCond %{QUERY_STRING} !r=n 
# if no token, rewrite and add token (so that directories with index.html won't get looped) 
RewriteRule ^(.+)\.html /$1/?r=n [L,QSA] 

但是,如果你只是有一帮叫做directory.html文件,directory2.htmldirectory3.html等等,你想要这样做,当有人输入http://domain.com/directory2/到他们的地址ba [R,他们的投放directory2.html的内容,这将是简单得多:

# check to make sure the request isn't actually for an html file 
RewriteCond %{THE_REQUEST} !^([A-Z]{3,9})\ /(.+)\.html\ HTTP 
# check to see if the html file exists (need to do this to strip off the trailing /) 
RewriteCond %{REQUEST_URI} ^/(.+)/$ 
RewriteCond %{DOCUMENT_ROOT}/%1.html -f 
# rewrite 
RewriteRule ^(.+)/$ /$1.html [L] 
+0

这工作,是一个很大的帮助。非常感谢你。 – Jakar

相关问题