Reputation: 1699
I have an existing site with a bunch of pages in /widgets/
and the new site also has pages in /widgets/
, some of which correspond to existing URLs. However, lots of other pages in that widgets section no longer exist and I just want to redirect them to /widgets
.
Basically, I want to write a rule that catches pages that are not found and redirect them to the landing page (/widgets/
) whilst allowing legit pages to be found.
Is it possible to write rules that will do this or do I need to manually redirect them all?
EDIT: As this is using a CMS (Craft) there are existing rules going on:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]`
Upvotes: 1
Views: 1014
Reputation: 45914
UPDATE: Since these pages only exist in the CMS itself and not as actual files on the filesystem then the CMS is also going to have to manage the redirection. Apache (.htaccess) does not know what is or is not a valid page, so unless you can determine a (filename) pattern to these redirects, you would need to specify each file/redirect manually in .htaccess.
Since this is an external redirect, it should come before your existing rules:
RewriteEngine On
RewriteBase /
# Redirect non-existent files within /widgets/ to /widgets
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^widgets/. /widgets [R=301,L]
# Existing rewrites
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]
Note that the RewriteRule
checks for the /widgets/
directory, not RewriteCond
directive - which would be less efficient.
I assume you already had a RewriteBase
directive in your original code? This is required since you have a relative path substitution in your RewriteRule
.
Upvotes: 1
Reputation: 627
You can catch missing files in htaccess with -f
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f // if not a file
RewriteCond %{REQUEST_FILENAME} !-d // if not a directory
RewriteCond %{REQUEST_URI} /widgets/(.*) // if in directory /widgets
RewriteRule ^.*$ /widgets [L] // redirect to /widgets
You can leave out the third line if you want to redirect missing pages outside the widgets sub directory.
Upvotes: 1