Search code examples
.htaccess

How to redirect entire site using .htaccess except for specific URLs?


I have to redirect the entire website to a new domain.

RedirectMatch 301 ^/.*$ http://new.example/

Except for the URLs of the form old.example/app/* and old.example/auth/*

For example, I would like to prevent the redirect for URLs /app/xyz and auth/login.


Solution

  • I assume you want to redirect to the same URL on the new domain, not to the document root, as in your example (that would be bad for SEO and seen as a soft-404 by search engines).

    Try the following, using mod_rewrite, at the top of your root .htaccess file instead:

    RewriteEngine On
    
    # Redirect to new domain except for URLs that start "/app/" or "/auth/"
    RewriteRule !^(app|auth)/ https://new.example%{REQUEST_URI} [R=301,L]
    

    The ! prefix on the RewriteRule pattern negates the regex, so it's successful when the requested URL path does not start /app/ or /auth/. https://example.com is the new domain and the same URL-path is used (ie REQUEST_URI server variable).

    Alternatively, if the URLs you want to exclude from the redirect are quite long or plentiful then you may choose to use conditions instead to exclude the specific URLs. For example:

    # Redirect to new domain except for URLs that start "/app/" or "/auth/"
    RewriteCond %{REQUEST_URI} !^/app/
    RewriteCond %{REQUEST_URI} !^/auth/
    RewriteRule ^ https://new.example%{REQUEST_URI} [R=301,L]
    

    If the old and new domains point to the same server then include a pre-condition that checks for the old domain. For example:

    RewriteCond %{HTTP_HOST} ^old\.example [NC]
    :