重写适用于目录。但不是文件

时间:2011-12-22 09:04:23

标签: php mod-rewrite

我的代码:

RewriteEngine on
RewriteBase /
RewriteRule ^article/([a-z]+)/?$ /index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/?$ /index.php?page=$1 [L]

这很有效。但是如果我提供文件名或目录,它就会失败。

我想要的是什么:

  • 如果用户请求目录或文件名,则重定向到主页。
  • 否则,应评估此规则:

    RewriteRule ^article/([a-z]+)/?$ /index.php?page=article&name=$1 [L] RewriteRule ^([a-z]+)/?$ /index.php?page=$1 [L]

我网站的根目录下有一个index.php文件:“http://mysite.com/index.php”

示例请求:

User typed url  --- Physical matched url  ---  Comments
----------------------------------------------------------

http://mysite.com/cinema    ---   http://mysite.com/index.php?page=cinema  --- display     cinema page
http://mysite.com/contacus    ---   http://mysite.com/index.php?page=contactus  ---     display contact us page
http://mysite.com/article/iphone    ---   http://mysite.com/index.php?page=article&name=iphone  --- display article
http://mysite.com/images    ---   http://mysite.com/index.php  --- redirect to index page, because it is a physical directory
http://mysite.com/js    ---   http://mysite.com/index.php  --- redirect to index page, because it is a physical directory

我的部分工作代码:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)/$ / [R,L]

RewriteRule ^article/([a-z]+)/?$  /index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/?$ /index.php?page=$1 [L]

如果我使用上面的代码,它可以部分工作。也就是说,

http://mysite.com/images  --- http://mysite.com/?page=images is displayed in address bar
http://mysite.com/images/  --- http://mysite.com/ is displayed in address bar

当我使用RewriteCond %{REQUEST_FILENAME} -f作为第二个条件时(在第一个条件的行之后),它将无效。

请帮帮我

2 个答案:

答案 0 :(得分:0)

当然,只有在的文件或目录存在时才应用重写规则吗?

尝试将这些行用作RewriteCond

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

答案 1 :(得分:0)

在我的本地主机上试了一下,这个工作正常:

RewriteEngine on

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

RewriteRule ^([^/\.]+)/?$ /index.php?page=$1 [L]
RewriteRule ^article/([^/\.]+)/?$ /index.php?page=article&name=$1 [L]

# For Future Reference, this works well for the final RewriteRule
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /index.php?page=$1&name=$2 [L]

作为替代解决方案,您还可以将所有网址重写为index.php:

RewriteEngine on

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

RewriteRule ^(.*)$ / [L]

第一个RewriteRule实际上会重定向浏览器,但第二个将只翻译它。这样做的好处是index.php将收到原始网址的REQUEST_URI:

$parts = explode('/', $_SERVER['REQUEST_URI']); // array( 0 => 'article', 1 => 'iphone', 2 => '')