开发者

Using mod_rewrite only if a 404 would have occured

I am in the process of converting a static website into one using a cms. I have the cms installed in a sub directory of the public directory. To avoid ending up with ugly domain names (http://example.com/cms/) is there an easy way using mod_rewrite to rewrite http://example.com/… to http://example.com/cms/… while ensuring that if the request wouldn't have ended in a 404, there is no redirect.

An example:

/
/cms/index.html
/cms/file.dat
/file.dat

If the user requests /index.html, they should get redirect开发者_JS百科ed to /cms/index.html, but if they request /file.dat, they shouldn't get redirected to /cms/file.dat because the file existed at the requested place

EDIT Thanks for the answers.


You could use the RewriteCond Directive to check whether there is an existing file that correspond to the requested URL, and only rewrite to your CMS if there is none.

Here is a simple example :

RewriteEngine on 

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php 

If there is no existing file that correspond to the requested URL, then that request is rewritten to index.php

You might also want to check for symbolic links and / or directories, btw...
For instance, here is a possibility that can be used when setting up a Zend Framework project :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

(Even though it links to ZF, it should be OK for quite many projects)


Try this rule:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^cms/ cms%{REQUEST_URI} [L]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜