2010-10-15 62 views
1

我在我的服务器上有html静态文件。我想访问规则 -使用.htaccess的URL重写帮助

  1. 如果用户访问http://example.com/test/他应该得到的文件http://example.com/test.html
  2. 的内容。如果用户访问http://example.com/test(没有尾随斜线),他被转到http://example.com/test/(运行规则1并获取文件test.html的内容012)
  3. 规则1和2只应在文件test.html存在时才会触发。

到目前为止,我有 -

Options All -Indexes -Multiviews 
# Do not return details of server 
ServerSignature Off 

<IfModule mod_rewrite.c> 
DirectorySlash Off 
RewriteEngine On 
RewriteBase/

# If it's a request to index.html 
RewriteCond %{THE_REQUEST} \ /(.+/)?index\.html(\?.*)?\ [NC] 
# Remove it. 
RewriteRule ^(.+/)?index\.html$ /%1 [R=301,L] 

# Add missing trailing slashes to directories if a matching .html does not exist. 
RewriteCond %{SCRIPT_FILENAME}/ -d 
RewriteCond %{SCRIPT_FILENAME}.html !-f 
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L] 

# If it's a request from a browser, not an internal request by Apache/mod_rewrite. 
RewriteCond %{ENV:REDIRECT_STATUS} ^$ 
# And the request has a HTML extension. Redirect to remove it. 
RewriteRule ^(.+)\.html$ /$1 [R=301,L] 

# If the request exists with a .html extension. 
RewriteCond %{SCRIPT_FILENAME}.html -f 
RewriteRule ^(.*)/?$ $1.html [QSA,L] 
</IfModule> 

虽然它适用于http://example.com/test,它失败了http://example.com/test/(500内部错误)

不应在倒数第二行采取尾随斜杠的护理?

[更新] 如果我用浓汤建议(以下的.htaccess),我得到两个http://example.com/testhttp://example.com/test/ 404(用斜线)

Options All -Indexes -Multiviews 
# Do not return details of server 
ServerSignature Off 

ErrorDocument 404 /404.html 

# Hide .htaccess 
<Files ~ "^\.ht"> 
Order allow,deny 
Deny from all 
</Files> 

<IfModule mod_rewrite.c> 
DirectorySlash On 
RewriteEngine On 
RewriteBase/

RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301] 
RewriteRule ^([^/]+)/$ $1.html [L] 

</IfModule> 

[更新2] 我已经放弃了。下面的代码可以工作,但不是强制以/(http://example.com/test/)结尾,而是删除最后一个斜杠(http://example.com/test)。在光明的一面,它确保内容仅由一个网址指向,保留SEO。我现在要和它一起生活。

Options All -Indexes -Multiviews 
# Do not return details of server 
ServerSignature Off 

ErrorDocument 404 /404.html 

# Hide .htaccess 
<Files ~ "^\.ht"> 
Order allow,deny 
Deny from all 
</Files> 

<IfModule mod_rewrite.c> 
DirectorySlash On 
RewriteEngine On 
RewriteBase/

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.+)/$ /$1 [R=301,L] 

# If the request exists with a .html extension. 
RewriteCond %{SCRIPT_FILENAME}.html -f 
# And there is no trailing slash, rewrite to add the .html extesion. 
RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L] 


</IfModule> 

回答

2

尝试下列规则:

RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301] 
RewriteRule ^([^/]+)/$ $1.html [L] 
+0

对不起,对于http://example.com/test和http://example.com/test/ – pravin 2010-10-15 10:53:12

+0

404 @pravin:哦,它固定。 – Gumbo 2010-10-15 11:04:08

+0

对不起,仍然404s – pravin 2010-10-15 11:20:23