Search code examples
wordpress.htaccesshttp-redirect

Redirect url of wordpress site on the basis of string using htaccess


I have a wordpress site eg. http://www.domain.com/ with custom theme hosted on a linux server and working fine. Some marketing strategy requires me to distinguish between 2 kinds of URLs (that they will be shooting from ads) and based on that redirect the site to different links.

eg:

If the URL contains /xyz/ ie:
http://www.domain.com/xyz/category/post I want it to be redirected to an intermediate page ie: http://www.domain.com/intermediate.php and if the url doesnt contain /xyz/ ie:
http://www.domain.com/category/post the post should show up as usual.

I found out that this cant be done inside the wordpress code as before the first hook is triggered, the url is processed and a 404 page is thrown.

The only way I can achieve this is by modifying .htaccess file.

I found a code which reads:

RewriteRule ^(.*)/xyz/(.*)$ http://www.domain.com/intermediate.php [L,R=301]

and second way reads:

RewriteCond %{REQUEST_URI} /xyz/
RewriteRule .* http://www.domain.com/intermediate.php

I am really confused about using it with the existing code in the htaccess file created by wordpress which reads:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

I tried merging the codes ie:

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /domain/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /domain/index.php [L]
RewriteCond %{REQUEST_URI} /xyz/
RewriteRule  RewriteRule ^(.*)/xyz/(.*)$ http://domain.com/intermediate.php
</IfModule>

but only one of them work at a time ie: when the redirection works, wordpress posts doesnt show up and vice versa. Kindly show me a better way.


Solution

  • Immediately after the RewriteEngine On and RewriteBase directives in the "existing" WordPress code try this:

    RewriteRule xyz/ http://www.domain.com/intermediate.php [L,R=301]
    

    This will search for "xyz/" anywhere in the requested URL and redirect when found. Note that in .htaccess files, the directory prefix (/ in this case) is removed from the URL path before pattern matching. So, a pattern that starts / will never match at the start of the URL.

    External redirects should generally come before internal rewrites, which is what the default WordPress directives do.

    The alternative method you mention is less efficient:

    RewriteCond %{REQUEST_URI} /xyz/
    RewriteRule .* http://www.domain.com/intermediate.php [R=301,L]
    

    This will effectively do the same thing but will result in every request being processed because of the generic .* pattern. Note that the REQUEST_URI does start with a / (directory prefix).