I am having one website and it is redirecting to five different index file randomly using php.
I want to redirect it using .htaccess , the same way it redirecting php.
I found that using htaccess we can redirect urls like,
Redirect 301 / http://www.xyzdomain.com/index.php
or
Redirect 302 / http://www.xyzdomain.com/index.php
Currently i am doing that with using php random array.
<?php
$urls = array("index.php",
"index2.php",
"index3.php",
"index4.php",
"index5.php");
$url = $urls[array_rand($urls)];
header("Location: http://www.xyzdomain.com/$url");
?>
Question: How to redirect multiple index randomly using .htaccess rules?
Not fully random like PHP code but you can achieve something similar using mod_rewrite using TIME_SEC variable that represents seconds value of the current time. Consider this code:
RewriteEngine On
RewriteBase /
# dont rewrite more than once
RewriteCond %{ENV:REDIRECT_STATUS} .+
RewriteRule ^ - [L]
# redirect all requests for php file to index file if %{TIME_SEC} is 0, 10, 20, 30, 40, 50
# or if %{TIME_SEC} is 1, 11, 21, 31, 41, 51
RewriteCond %{TIME_SEC} [01]$
RewriteRule ^.+?\.php$ index.php [L,NC]
# redirect all requests for php file to index file if %{TIME_SEC} is 2, 12, 22, 32, 42, 52
# or if %{TIME_SEC} is 3, 13, 23, 33, 43, 53
RewriteCond %{TIME_SEC} [23]$
RewriteRule ^.+?\.php$ index2.php [L,NC]
# redirect all requests for php file to index file if %{TIME_SEC} is 4, 14, 24, 34, 44, 54
# or if %{TIME_SEC} is 5, 15, 25, 35, 45, 55
RewriteCond %{TIME_SEC} [45]$
RewriteRule ^.+?\.php$ index3.php [L,NC]
# redirect all requests for php file to index file if %{TIME_SEC} is 6, 16, 26, 36, 46, 56
# or if %{TIME_SEC} is 7, 17, 27, 37, 47, 57
RewriteCond %{TIME_SEC} [67]$
RewriteRule ^.+?\.php$ index4.php [L,NC]
# redirect all requests for php file to index file if %{TIME_SEC} is ending in 8, 9
RewriteCond %{TIME_SEC} [89]$
RewriteRule ^.+?\.php$ index5.php [L,NC]
To redirect individual files, like example.com/oldfile.htm to newfile.htm you can use a 301 redirect like this: http://www.inmotionhosting.com/support/website/redirects/setting-up-a-301-permanent-redirect-via-htaccess
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With