Reputation: 304
I'm trying to load files from a sub-directory if they don't exist in the root, and only do so if they do indeed exist in the sub-directory.
RewriteEngine On
# If requested resource exists as a file or directory, skip next two rules
RewriteCond %{DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule (.*) - [S=2]
# Requested resource does not exist, do rewrite if it exists in /pages
RewriteCond %{DOCUMENT_ROOT}/pages/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/pages/$1 -d
RewriteRule (.*) /pages/$1 [L]
# Else rewrite requests for non-existent resources to /index.php
# Disabled to see when the files fail to load
#RewriteRule (.*) /index.php?q=$1 [L]
# Remove file extention
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
# Error Documents
ErrorDocument 400 /400.shtml
ErrorDocument 404 /404.shtml
ErrorDocument 500 /500.shtml
The following URL's work
The following does not work
Does anyone know what I'm doing wrong in this scenario? Also, I'm sure its related to how I'm addressing the missing file redirect, but the 404.shtml page does not load when the server returns a 404 error.
Upvotes: 1
Views: 2002
Reputation: 143906
The reason is that you're checking if a file exists while it has its extension removed. So of course, it's not going to exist. Additionally, your rules that stick the extensions back on doesn't know to also check the /pages/ directory.
Try maybe something like:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/pages/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/pages/$1 -d
RewriteRule (.*) /pages/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f
RewriteRule ^(.*)$ /$1.html [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(.*)$ /$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/pages/$1\.html -f
RewriteRule ^(.*)$ /pages/$1.html [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/pages/$1\.php -f
RewriteRule ^(.*)$ /pages/$1.php [L]
Upvotes: 3