如何只为.htaccess重写规则指定一个目录?

时间:2013-02-18 13:15:13

标签: .htaccess mod-rewrite

我将重写规则正常工作,格式为site.com/dir/page1.php的所有网页都转换为格式site.com/page1。我通过以下方式实现了这一目标:

# 1. turn on the rewriting engine
RewriteEngine On

# 2. remove the www prefix
RewriteCond %{HTTP_HOST} ^www\.site\.com [NC] 
RewriteRule ^(.*)$ http://site.com/$1 [L,R=301]

# 3.  send all non-secure pages to secure pages
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# 4. if 404 not found error, go to homepage
ErrorDocument 404 /index.php

# 5. if url received with trailing slash (e.g. http://domain/test/) then go to correct page (e.g. http://domain/pages/test.php)
RewriteRule ^([^.]+)/$ includes/$1.php

# 6. if url received WITHOUT trailing slash (e.g. http://domain/test) then go to correct page (e.g. http://domain/pages/test.php)
RewriteRule ^([^.]+)$ includes/$1.php

我现在在site.com/blog/设置了一个博客,当我尝试访问博客时,它正在显示主页(即404错误)。

认为错误发生在第5部分和第6部分,并且我需要指定重写规则专门针对'includes'目录?但我可能是错的,任何帮助表示感谢,谢谢!

更新

我试过这个解决方案忽略了'blog'目录:

How to configure .htaccess file for rewrite rules to get rid of extensions, trailing slashes, www?

#skip wordpress site which starts with blog
RewriteCond %{REQUEST_URI} !^/blog [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

但不幸的是,这对我不起作用。

1 个答案:

答案 0 :(得分:1)

为了防止重写blog/,请将以下内容放在规则5,6之前(这是一般的重写):

# Do not apply the following to the blog
RewriteCond %{REQUEST_URI} !^/blog

# 5. if url received with trailing slash (e.g. http://domain/test/) then go to correct page (e.g. http://domain/pages/test.php)
# Merged 5 & 6 together by making the trailing slash optional /?
RewriteRule ^([^.]+)/?$ includes/$1.php

另一种可能性是防止对存在的任何目录进行重写:

# Do not apply the following to actual existing files and directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Merged 5 & 6 together by making the trailing slash optional /?
RewriteRule ^([^.]+)/?$ includes/$1.php