envysea
envysea

Reputation: 1031

.htaccess 301 redirect specific URLs with a fallback

I am migrating a domain.

I have some URLs where I need to redirect them to a specific page, but everything else can be a blanket fallback. I need to maintain query strings as well.

E.g.:

Manual URLs:

http://example.com/i-am-manual-redirect   =>    https://example2.com/this-is-not-the-same-URL
http://example.com/i-am-manual-redirect2   =>    https://example2.com/somewhere-else

Then the fallback for everything else:

http://example.com/same   =>    https://example2.com/same
http://example.com/blah   =>    https://example2.com/blah

Currently have:

# Manual Redirects
RedirectMatch 301 ^/i-am-manual-redirect https://example2.com/this-is-not-the-same-URL
RedirectMatch 301 ^/i-am-manual-redirect2 https://example2.com/somewhere-else

# Fallback
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example2.com/$1 [L,R=301,NC]

But anytime I add the fallback, the manual redirects don't work.

Upvotes: 1

Views: 1323

Answers (1)

user2493235
user2493235

Reputation:

You need to prevent the RewriteRule from processing your manual ones, or do it all with mod_rewrite. Mod_rewrite is processed first, I think. Or change all to use mod_rewrite. Here's an update to what you have:

# Manual Redirects
Redirect 301 /i-am-manual-redirect https://example2.com/this-is-not-the-same-URL
Redirect 301 /i-am-manual-redirect2 https://example2.com/somewhere-else

# Fallback
RewriteCond %{REQUEST_URI} !=/i-am-manual-redirect
RewriteCond %{REQUEST_URI} !=/i-am-manual-redirect-2
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example2.com/$1 [L,R=301]

Do you know that your first two go to https:// and your fallback to http://? Just checking.

NC was not needed on the rule as no characters are specified in the regex.

No need to use RedirectMatch as you're specifying the full URL, since the query string is not matched against. In both cases here it's just passed through as you want.

Upvotes: 2

Related Questions