Home > database >  .htaccess redirect if match pattern else do nothing
.htaccess redirect if match pattern else do nothing

Time:10-21

I have three scenario to satisfy

Scenarios are

  1. Need to redirect if www.example.com then to www.example.com/a-a
  2. Need to redirect if www.example.com/pages then to www.example.com/a-a/pages
  3. Need not to redirect if www.example.com/b-b then go as it is www.example.com/b-b
  4. Need not to redirect if www.example.com/b-b/pages then go as it is www.example.com/b-b/pages

My code is satisfying the first two scenarios and forcing always the same. I couldn't bring the not condition.

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/a-a(/.*)?$
RewriteRule ^(.*)$ /a-a/$1 [L,R=301]

RewriteCond %{REQUEST_URI} ^/b-b(/.*)?$
RewriteRule ^(.*)$  [L,R=301]  # do nothing here and not to do the previous condition

Second condition is forcing always to www.example.com/a-a/b-b I do not want this.

CodePudding user response:

The second rule isn't actually doing anything since a request for /b-b is caught by the first rule. (The second rule is invalid anyway since you are missing the substitution string it would result in an internal rewrite to [L,R=301] - which is likely to "break horribly".)

You don't need a second rule. You can create an exception on the first rule with a RewriteCond directive, in the same way you created an exception to exclude /a-a (and redirecting to itself).

For example:

RewriteCond %{REQUEST_URI} !^/b-b(/.*)?$
RewriteCond %{REQUEST_URI} !^/a-a(/.*)?$
RewriteRule ^(.*)$ /a-a/$1 [L,R=301]

You will need to clear your browser cache before testing since the erroneous (301 - permanent) redirect to /a-a/b-b will have been cached. To avoid caching issues test with 302 (temporary) redirects.

  • Related