繁体   English   中英

使用PHP和.htaccess的RewriteCond

[英]RewriteCond using PHP and .htaccess

我正在尝试使用PHP和htaccess执行条件RewriteCond。 这个想法是从JSON文件中读取个性网址,并在PHP文件中进行相应的重定向。

如果需要使用标头将其重定向到另一个URL,则可以使用它。

的.htaccess

RewriteEngine On
RewriteCond $2 !^(redirect\.php)
RewriteRule ^(.*)$ redirect.php?l=$2 [L]

redirect.php

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$found = true;
if($found){
  header('HTTP/1.1 301 Moved Permanently');
  header(sprintf('Location: %s', 'https://www.google.com'));
}else{//no redirection is need, stay in the same URL
  header('HTTP/1.1 301 Moved Permanently');
  header(sprintf('Location: %s', $url)); //throw error ERR_TOO_MANY_REDIRECTS
}

但是,如果不满足如图所示的“找到”条件,并且现在我试图使用$ url变量重定向到同一页面,则不应重定向它,并且它返回错误“ ERR_TOO_MANY_REDIRECTS”。 还有另一种方法可以有效地处理这部分代码吗?

因此,根据评论,我想我可以提供适当的答案。
因此,您的目标是对所调用的URL做出反应并根据URL是否对您的系统“已知”( $found )进行重定向? 如果是这种情况: $found为true时,您要重定向到Google是否正确? 我真的不明白它的目的-也许你是说!$found 那么所有未知请求都被重定向到Google?

基于这些假设,您仍然可以在自己的服务器上显示来自其他PHP或HTML文件的内容,而无需重定向客户端。

假设用户调用https://example.org/some/fancy/page 这将被重定向到您的redirect.php ,您可以在some/fancy/page$_GET["l"]读取some/fancy/page部分。

当您的JSON文件看起来像这样(如果此假设完全错误,请提供一个实际示例)。

{
    "some/fancy/page": "views/page1.html",
    "some/other/page": "views/page2.html"
}

然后您的redirect.php可以检查此JSON字典中是否存在已知和未知请求,并根据结果重定向或加载内容:

$called = $_GET["l"]; // contains "some/fancy/page"
$json = json_decode(file_get_contents("path_to_json"), true);

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Check if the called URL is part of your JSON file.
$found = isset($json[$called]);

if(!$found) { // Note the ! from my assumption
  // We did not find this -> redirect to google
  header('HTTP/1.1 301 Moved Permanently');
  header(sprintf('Location: %s', 'https://www.google.com'));
} else {
  // Page is found on the local server - load from the file listed in JSON
  // (views/page1.html) and send it to the client.
  echo file_get_contents($json[$called]);  

  /**
  // In case your JSON contains external URLs, e.g. https://fancypage.org for "some/fancy/page", you can still use redirection
  // This will, however, not end up on your own server and thus will not trigger the rewrite rule.
  header('HTTP/1.1 301 Moved Permanently');
  header(sprintf('Location: %s', $json[$called]));
  **/
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM