Yii2: Host-based routing for http and https requests

Created on 7 Oct 2016  ·  21Comments  ·  Source: yiisoft/yii2

What steps will reproduce the problem?

Проблема строится на том, что текущая реализация роутера не предусматривает вариацию, когда запрос к домену идёт через оба протокола. Например, имеется такой конфиг:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        "http://you-domain.net/some/path" => 'controller/action',
    ],
],

На локальном сервере всё работает как ожидается, но на продакшене, где настроен https, данный роут перестаёт распознаваться, т.к. там getHostInfo() уже возвращает https://you-domain.net.

Я пробовал указывать значение без протокола (то есть "you-domain.net/some/path" => 'controller/action'), но в таком случае роут вовсе не был добавлен в UrlManager.

What is the expected result?

Если я не укажу протокол, то сверка роута должна происходить только по имени хоста, без проверки протокола.

Additional info

| Q | A |
| --- | --- |
| Yii version | 2.0.9 |
| PHP version | 7.0.11 |
| Operating system | Docker 1.12.1 (php:7.0.11-fpm) |

enhancement

Most helpful comment

Perhaps, it should be possible to use :// as host involving indicator.

//example.com is standard syntax for protocol relative URLs: https://en.wikipedia.org/wiki/Uniform_Resource_Locator#prurl

All 21 comments

Probably related to #3047.

Nope, it's different. The problem here is that in domain-relative URL rules you have to specify http or https and can't use something which works for both.

@samdark, я близок к завершению PR. Только я не привязывался конкретно к http или https, а делаю поддержку любого протокола.

Use optional s for protocol specification:

'rules' => [
        "http(s)?://you-domain.net/some/path" => 'controller/action',
    ],

IMO UrlRule should have property like $validSchemas with value like ['https', 'http']. So if we have rules like:

['pattern' => 'login', 'validSchemas' => ['https'], ...],
['pattern' => 'http://exaple.com/home', 'validSchemas' => ['https', 'http'], ...]

then:

  • https://example.com/login will match first rule
  • http://example.com/login will NOT match first rule
  • http://example.com/home will match second rule
  • https://example.com/home will match second rule

UrlNormalizer could use UrlRule::$validSchemas to handle redirection to valid schema.

@klimov-paul, nice try, but it doesn't work. Inside UrlRule Yii2 escape any characters like (, ?, ) and final regex contains something like: http\(s\)\?....

nice try, but it doesn't work. Inside UrlRule Yii2 escape any characters like (, ?, ) and final regex contains something like: http(s)?....

Sorry, this one works:

'rules' => [
        "<protocol:http|https>://you-domain.net/some/path" => 'controller/action',
    ],

@klimov-paul, ok, it works, thanks for solution.

But I think that current behavior is not expected, because I don't see any error, or something else, that explain, why rule without scheme was not added to UrlManager. My proposal is simple and expected way to define route, that match only for specified host without reference to scheme.

My proposal is simple and expected way to define route, that match only for specified host without reference to scheme.

Sorry, but I can not see any proposal from your side - only a complain.

Protocol mention is necessary to determine whether URL rule involves host name or not.
Unless there is a syntax which allows to explicitly determine UrlRule contains domain, but do not contain protocol at the same time - there is not much can be done here.

I can not see any proposal from your side

My proposal is implement such syntax for routes:

'rules' => [
    "you-domain.net/some/path" => 'controller/action',
],

you-domain.net can be extracted by regex ^(any-string-with-dots)/. Or I don't see some case?

'rules' => [
    '//example.com/some/path' => 'controller/action',
],

?

@rob006, yes, it will be better, because I found, that path can contain dots or hostname can be without dots.

My proposal is implement such syntax for routes:

Such syntax is unacceptable: string you-domain.net can be a valid URL part after domain name.
For example:

http://domain.com/another.domain.com

Or to have more real world example:

http://domain.com/file.html

//example.com/home?

Similar problem. While usually double slash (//) is not used in URLs it is still valid. For example:

http://domain.com/catalog//1

We're expecting it at the very beginning, not in the middle.

I think protocol relative URLs support is a good idea.

Perhaps, it should be possible to use :// as host involving indicator.

Perhaps, it should be possible to use :// as host involving indicator.

//example.com is standard syntax for protocol relative URLs: https://en.wikipedia.org/wiki/Uniform_Resource_Locator#prurl

Yes. //, not ://.

Resolved by 16a5777

Or not?

I think it's still not resolved. That one is a about creating URLs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rosancoderian picture rosancoderian  ·  46Comments

samdark picture samdark  ·  63Comments

sepidemahmoodi picture sepidemahmoodi  ·  104Comments

njasm picture njasm  ·  44Comments

schmunk42 picture schmunk42  ·  47Comments