我有一个网站,它使用 php 随机重定向到五个不同的索引文件。
- www.xyzdomain.com/index.php
- www.xyzdomain.com/index2.php
- www.xyzdomain.com/index3.php
- www.xyzdomain.com/index4.php
- www.xyzdomain.com/index5.php
我想使用 .htaccess 重定向它,就像重定向 php 一样。
我发现使用 htaccess 我们可以像这样重定向 url,
Redirect 301 / http://www.xyzdomain.com/index.php
或
Redirect 302 / http://www.xyzdomain.com/index.php
目前我正在使用 php 随机数组来做到这一点。
<?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");
?>
问题:如何使用.htaccess规则随机重定向多个索引?
最佳答案
不像 PHP 代码那样完全随机,但您可以使用 mod_rewrite
使用 TIME_SEC
变量实现类似的功能,该变量表示当前时间的秒值。考虑这段代码:
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]
关于php - 使用 .htaccess 进行多 url 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967179/