.htaccess PHP - 仅在输入域时防止重写

时间:2014-12-11 16:58:59

标签: php apache .htaccess mod-rewrite url-rewriting

我的网站位于

application
  controllers
  views
  ...
  public <- the root of the site
    index.php <- entry point
    css
    ...

所以网址是http://localhost/application/public。我希望当用户只输入http://localhost/application/public时除了调用index.php而不显示它之外什么都不做。

以下是一些例子:

http://localhost/application/public - &gt; http://localhost/application/publichttp://localhost/application/public/

BUT

http://localhost/application/public/asdf - &gt;在内部重写http://localhost/application/public/index.php并仅显示http://localhost/application/public/asdf

我写了.htaccess。唯一的问题是,在输入http://localhost/application/public时,它会打开http://localhost/application/public/index.php而不是http://localhost/application/public

还有一件事 - 我希望重写现有目录,因此不应将现有文件重写为index.php所以基本上http://localhost/application/public/css应该重写为index.php。我想要的原因是省略403 Forbidden错误,并告诉用户该路径不存在。

htaccess的

Options +FollowSymLinks -MultiViews -Indexes
RewriteEngine On
RewriteBase /application/public/

#Remove trailing slash
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ $1 [R=301,L]

#Do the rewriting
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [NC,L]

我提出RewriteCond %{REQUEST_FILENAME} !-d的原因是为了防止http://localhost/application/public重写。如果重写http://localhost/application/public,则会加载http://localhost/application/public/index.php

实际上我知道RewriteCond %{REQUEST_FILENAME} !-d需要进行一些修改。我希望root, public 文件夹不被重写,它应该是唯一的例外。所有其他物理文件夹,如css,js,都必须重写,就像不存在一样。不应重写文件。谢谢!

1 个答案:

答案 0 :(得分:1)

好的,我想我找到了解决方案。

Options +FollowSymLinks -MultiViews -Indexes
RewriteEngine On
RewriteBase /application/public/

RewriteRule ^(css/?|js/?)$ index.php [NC,L] <- Folders css, js will be rewritten, but root directory won't be rewritten. Files inside them also won't be rewritten.

#Remove trailing slash
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ $1 [R=301,L]

#Do the rewriting
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [NC,L]