htaccess url redirect for all urls except one

To redirect all URLs to a new destination in .htaccess except for one specific page, use RewriteCond to define an exception based on the REQUEST_URI before the RewriteRule. Place this code at the top of your .htaccess file, ensuring the exception URL starts with a forward slash.

Code Example: Redirect All Except One Page 

This example redirects everything to https://new-site.com except for /keep-this-page.html.

apache

RewriteEngine On
# Skip redirection for /keep-this-page.html
RewriteCond %{REQUEST_URI} !^/keep-this-page\.html$ [NC]
# Redirect all other pages permanently (301)
RewriteRule ^(.*)$ https://new-site.com/ [R=301,L]

Key Details

  • Exception Formulation: The ! means “does not match”. The ^ indicates the start of the URI.
  • Avoid Loops: Ensure the file you are excluding is not the same as your destination, or a redirect loop will occur.
  • Case Insensitivity: The [NC] flag makes the exception case-insensitive.
  • Testing: Use [R=302,L] (temporary) first to avoid caching issues in your browser while testing, then change to [R=301,L] (permanent) when ready.

Example: Excluding Multiple URLs

You can stack RewriteCond lines to exclude multiple paths (e.g., a page and a stylesheet). 

apache

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/keep-this-page\.html$ [NC]
RewriteCond %{REQUEST_URI} !^/assets/.*$ [NC]
RewriteRule ^(.*)$ https://new-site.com/ [R=301,L]