php - 使用 .htaccess 进行多 url 重定向

标签 php .htaccess mod-rewrite redirect url-redirection

我有一个网站,它使用 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/

相关文章:

.htaccess - htaccess RewriteEngine 适用于 HTTP 但不适用于 HTTPS

.htaccess - 制作重写规则删除 .php 扩展名?

php - 通过Android App注册时Mysql查询出错

apache - Vue.js + Apache ,如何编写多入口的重定向规则?

apache - 重定向到 rtmp 协议(protocol)时,RewriteRule 将子文件夹附加到 url

linux - 服务器总是在 url 中添加后缀

ruby-on-rails - 需要将 WP 博客与 Heroku 上的 Rails 应用程序链接起来

php - 如何在php中设置小数点最多8位小数

php - 在 mime smtp 中添加 pdf 附件

php - 删除重复条目