2011-12-08 58 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

相關問題