Using mod_rewrite only if 404 happened

I am going to convert a static website to one using cms. I have cms installed in a subdirectory of a shared directory. To avoid getting ugly domain names ( http://example.com/cms/ ) there is an easy way to use mod_rewrite to rewrite http://example.com/ ... http://example.com/cms/ ... provided that if the request is not ended in 404, there is no redirect.

Example:

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

      

If the user asks for /index.html they should be redirected to /cms/index.html, but if they ask for /file.dat they shouldn't be redirected to /cms/file.dat because the file exists in the requested location

EDIT Thanks for the answers.

+2


source to share


2 answers


You can use the RewriteCond Directive to check if an existing file exists that matches the requested URL and only rewrite it to the CMS if not.

Here's a simple example:

RewriteEngine on 

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

      

If there is no existing file matching the requested url, this request is rewritten to index.php



You can also check for symbolic links and / or directories, btw ...
For example, here's a feature 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 references ZF, it should be ok for quite a few projects)

+5


source


Try the following rule:



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

      

+2


source







All Articles