views:

82

answers:

2

A fairly basic htaccess question, but I don't use it much, so i have no idea. I want to check if the requested file exists. If it does, forward to one page, and if not forward to another page and pass the requested path as GET.

Thanks in advance.

+2  A: 
RewriteEngine On

# check if requested file or directory exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

# if not, pass it to index.php
RewriteRule ^(.*) index.php?page=$1 [QSA]

As Gumbo suggested, you can repeat the condition without the ! if you also want to rewrite the URL when a file exists. Maybe you want to 'protect' your real files and folders with this method.

Daniel Vassallo
Thanks, and may I ask what the [QSA] does?
Dylan
[QSA] preserves the query string.
Daniel Vassallo
is there any way to pass the full path instead of just the filename?
Dylan
Try using the {REQUEST_URI} in the RewriteRule. It will get replaced with the path.
Daniel Vassallo
+1  A: 

Use the -f expression in a RewriteCond condition to test if the given path points to an existing regular file:

RewriteEngin on

# file exists    
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ one-page [L]

# file does not exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ another-page [L]

The initial requested URI should then be available in an environment variable.

Gumbo
how could i check to make sure that the filename isn't index.php before i forward it to a page?
Dylan
@Dylan: You can put that into your rule like `RewriteRule !^index\.php$`. Or you attach an additional condition: `RewriteCond %{REQUEST_URI} !^/index\.php$`.
Gumbo