切换HTTP / HTTPS协议

时间:2014-10-02 03:02:33

标签: php

我想找到一个在PHP服务器上切换HTTP和HTTPS协议的解决方案,这个解决方案必须来自本地网络和Internet网络。

方案:

            DNS: domain.com
                IP: x.x.x.x <╌┬╌> IP: 192.168.1.1
                              ┆
┌──────────┐       HTTP 80┌───┴────┐      HTTP 8000┌────────┐
│ INTERNET ╞══════════════╡ ROUTER ╞═══════════════╡ SERVER │ IP: 192.168.1.2
│          ╞══════════════╡        ╞═══════════════╡        │ DNS: SERVER.local
└────╥╥────┘     HTTPS 443└───╥╥───┘     HTTPS 8001└────────┘
     ║║                       ║║
 ┌───╨╨───┐               ┌───╨╨───┐
 │ CLIENT │               │ CLIENT │
 └────────┘               └────────┘

问题:

  • 从本地网络,客户端必须重定向:

    http://SERVER.local:8000(端口8000显式)到https://SERVER.local:8001(端口8001显式)或从http://192.168.1.2:8000https://192.168.1.2:8001

  • 从Internet网络,客户端必须重定向:

    http://domain.com(隐式端口80)到https://domain.com(隐式端口443)或从http://x.x.x.xhttps://x.x.x.x

问题:

  • 如何检测客户端(Internet或本地网络)的来源以将其切换到正确的URL?

欢迎支持IPv6的全球解决方案!谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

switch ($_SERVER['HTTP_HOST']) {
    case 'SERVER.local:8000': {
        header('Location: https://SERVER.local:8001/' . $_SERVER['REQUEST_URI']);
        exit;
    }
    case '192.168.1.2:8000': {
        header('Location: https://192.168.1.2:8001/' . $_SERVER['REQUEST_URI']);
        exit;
    }
    case 'domain.com:80': {
        header('Location: https://domain.com/' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

答案 1 :(得分:0)

我最终使用此方法而不依赖任何静态IP地址或DNS记录:

define('HTTP_LOCAL_PORT', 8000);
define('HTTPS_LOCAL_PORT', 8001);

define('HTTPS', isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN));
define('REQUEST_URL', (HTTPS ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
define('REQUEST_HOST', parse_url(REQUEST_URL, PHP_URL_HOST));
define('REQUEST_PORT', parse_url(REQUEST_URL, PHP_URL_PORT));
define('LOCAL_REMOTE', REQUEST_PORT == HTTP_LOCAL_PORT || REQUEST_PORT == HTTPS_LOCAL_PORT);
define('HTTP_REQUEST_URL', 'http://'.REQUEST_HOST.(LOCAL_REMOTE?':'.HTTP_LOCAL_PORT:'').$_SERVER['REQUEST_URI']);
define('HTTPS_REQUEST_URL', 'https://'.REQUEST_HOST.(LOCAL_REMOTE?':'.HTTPS_LOCAL_PORT:'').$_SERVER['REQUEST_URI']);

if REQUEST_URL = 'http://domain.com/uri'
 > HTTPS_REQUEST_URL = 'https://domain.com/uri'

if REQUEST_URL = 'http://x.x.x.x/uri'
 > HTTPS_REQUEST_URL = 'https://x.x.x.x/uri'

if REQUEST_URL = 'http://SERVER.local:8000/uri'
 > HTTPS_REQUEST_URL = 'https://SERVER.local:8001/uri'

if REQUEST_URL = 'http://192.168.1.2:8000/uri'
 > HTTPS_REQUEST_URL = 'https://http://192.168.1.2:8001/uri'