强制Canonical使用HTTPS

Ric*_*ing 15 php zend-framework view-helpers zend-view zend-framework2

我希望我的客户部分是https,例如注册,登录,个人详细信息,订单详细信息等.我已经设置了包含https方案的路线(我可以通过https访问客户部分)但我不能强制我的链接使用https:

<a class="register" href="<?php echo $this->url('customer/default', array('controller' => 'registration', 'action' => 'index'), array('scheme' => 'https', 'force_canonical' => true,)); ?>">Register</a>
Run Code Online (Sandbox Code Playgroud)

我得到了什么: http://myproject.dev/customer/registration

我想要的是: https://myproject.dev/customer/registration

它似乎使用当前的方案 - 所以如果我在http上,那么网址是http,如果我在https上,那么网址是https.

我如何强制$this->url一直使用该https方案?

'router' => array(
  'routes' => array(
    'customer' => array(
      'type' => 'Zend\Mvc\Router\Http\Literal',
      'options' => array(
        'route' => '/customer',
        'scheme' => 'https',
        'defaults' => array(
          '__NAMESPACE__' => 'Customer\Controller',
          'https' => true,
          'controller' => 'Index',
          'action' => 'index',
        ),
      ),
      'child_routes' => array(
        'default' => array(
          'type' => 'Segment',
          'options' => array(
            'route' => '/[:controller[/:action]]',
            'scheme' => 'https',
            'constraints' => array(
              'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
              'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
            ),
            'defaults' => array(
            ),
          ),
        ),
      ),
    ),
  ),
),
Run Code Online (Sandbox Code Playgroud)

[编辑]

myproject.dev是我的本地机器,我已经更改了我的主机vhosts文件.我已经设置了我的vhosts文件来接受ssl,这不是问题.

我已将路由类型更改为Zend\Mvc\Router\Http\Scheme并添加了scheme选项,但会生成以下url:https://myproject.dev:80/registration生成一个,SSL connection error因为它正在尝试连接到端口80!

当我改变了child_routes typescheme生成的URL是:https://myproject.dev:80/customer

[编辑]

作为一个临时解决方案,如果用户尝试访问非安全方案的客户部分,我正在进行htaccess重定向:

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^/customer/?.*$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Run Code Online (Sandbox Code Playgroud)

我不喜欢这种方法,因为它不应该是必要的!

[编辑]

虽然我希望我的客户部分是https,但我不希望网站的其余部分.

小智 5

使用Zend\Uri\UriFactory;

在您的操作之上添加以下代码或在插件中创建方法.

$uri = $this->getRequest()->getUri();
        $uri = (string) $uri;
        $url = UriFactory::factory($uri);
        $http = 'http';
        $http_current = $url->getScheme();
        if($http == $http_current){
            $url->setScheme('https');
            return $this->redirect()->toUrl($url);
        }
Run Code Online (Sandbox Code Playgroud)


Chr*_*urd 2

使用 ServerUrl 和 URL 视图帮助器的组合来构建您的 URL,EG:

<?php
$this->getHelper('ServerUrl')->setScheme('https')
?>
<a href="<?php echo $this->serverUrl($this->url('customer/default', array('controller' => 'registration', 'action' => 'index'), array('force_canonical' => true,))); ?>">Link Caption</a>
Run Code Online (Sandbox Code Playgroud)

这将强制链接完全限定而不是相对链接,并将强制方案为 https,而不会导致端口指定错误的问题。