Skip to content

[2.2][Routing] hostname pattern for routes #3378

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 12, 2012

Conversation

arnaud-lb
Copy link
Contributor

Bug fix: no
Feature addition: yes
Fixes the following tickets: #1762, #3276
Backwards compatibility break: no
Symfony2 tests pass: yes

This adds a hostname_pattern property to routes. It works like the pattern property (hostname_pattern can have variables, requirements, etc). The hostname_pattern property can be set on both routes and route collections.

Yaml example:

# Setting the hostname_pattern for a whole collection of routes

AcmeBundle:
    resource: "@AcmeBundle/Controller/"
    type: annotation
    prefix: /
    hostname_pattern: {locale}.example.com
    requirements:
        locale: en|fr

# Setting the hostname_pattern for single route

some_route:
    pattern: /hello/{name}
    hostname_pattern: {locale}.example.com
    requirements:
        locale: en|fr
        name: \w+
    defaults:
        _controller: Foo:bar:baz

Annotations example:

<?php

/**
 * Inherits requirements and hostname pattern from the collection
 * @Route("/foo")
 */
public function fooAction();

/**
 * Set a specific hostnamePattern for this route only
 * @Route("/foo", hostnamePattern="{_locale}.example.com", requirements={"_locale="fr|en"})
 */
public function fooAction();

Performance:

Consecutive routes with the same hostname pattern are grouped, and a single test is made against the hostname for this group, so the overhead is very low:

@Route("/foo", hostnamePattern="a.example.com")
@Route("/bar", hostnamePattern="a.example.com")
@Route("/baz", hostnamePattern="b.example.com")

is compiled like this:

if (hostname matches a.example.com) {
    // test route "/foo"
    // test route "/bar"
}
if (hostname matches b.example.com) {
    // test route "/baz"
}

The PR also tries harder to optimize routes sharing the same prefix:

@Route("/cafe")
@Route("/cacao")
@Route("/coca")

is compiled like this:

if (url starts with /c) {
    if (url starts with /ca) {
        // test route "/cafe"
        // test route "/cacao"
    }
    // test route "/coca"
}

@Koc
Copy link
Contributor

Koc commented Feb 16, 2012

Interesting. Have you looked at #3057, #3002?

Killer feature of #3057 : multiple hostnames per route.

@arnaud-lb
Copy link
Contributor Author

@Koc yes, the main difference is that this PR allows variables in the hostname pattern, with requirements, etc just like the path pattern. The other PRs use a _host requirement, which works like the _method requirement (takes a list of allowed hostnames separated by |).

Killer feature of #3057 : multiple hostnames per route.

If you have multiple tlds you can easily do it like this:

hostbased_route:
  pattern:  /
  hostname_pattern: symfony.{tld}
  requirements:
     tld: org|com

Or with completely different domain names:

hostbased_route:
  pattern:  /
  hostname_pattern: {domain}
  requirements:
     domain: example\.com|symfony\.com

Requirements allow DIC %parameters%, so you can also put you domains in your config.yml.

@Koc
Copy link
Contributor

Koc commented Feb 16, 2012

wow, nice! So looks like this PR closes my #3276 ticket?

@arnaud-lb
Copy link
Contributor Author

Yes, apparently :)

@Koc
Copy link
Contributor

Koc commented Feb 16, 2012

I cann't find method ParameterBag::resolveValue calling in this PR, like here https://github.com/symfony/symfony/pull/3316/files

@arnaud-lb
Copy link
Contributor Author

I think it's in core already

@Koc
Copy link
Contributor

Koc commented Feb 16, 2012

@dlsniper
Copy link
Contributor

This PR looks great, it's something like this I've been waiting for.

I know @fabpot said he's working on something similar but I think if he agrees with this it could be a great addition to the core.

@fabpot , @stof any objections about this PR if gets fully done?

@stof
Copy link
Member

stof commented Feb 16, 2012

Well, we already have 2 other implementations for this stuff in the PRs. @fabpot please take time to look at them

@stof
Copy link
Member

stof commented Feb 16, 2012

This one is absolutely not tested and seems to break the existing tests according to the description. So it cannot be reviewed as is.

@dlsniper
Copy link
Contributor

@stof I understand it's a WIP but the other PRs where ignored as well and like you've said, there's a bunch of PRs already on this issue all doing a thing or another. So an early feedback on this, or any other, could lead it to the right path in order to finally solve this issue.

@arnaud-lb
Copy link
Contributor Author

Added tests; others are passing now

@arnaud-lb
Copy link
Contributor Author

I'm going to add support for the Apache dumper and the XML loader; does this PR have a chance to be merged ? cc @fabpot @stof

@stof
Copy link
Member

stof commented Feb 22, 2012

@arnaud-lb We need to wait @fabpot's mind about the way he prefers to implement it to know which one can be merged.

@masterspambot
Copy link

Forked @arnaud-lb hostname_pattern to add XML parasing support.

@stof
Copy link
Member

stof commented Apr 3, 2012

@arnaud-lb Please rebase your branch. It conflicts with master because of the move of the tests

@fabpot @vicb ping

@dlsniper
Copy link
Contributor

Hi,

If @arnaud-lb won't be able to rebase this I could help with some work on this but there's still the problem of actually choosing the right PR(s) for this issue. @blogsh says in his last commit that this PR is a bit better in his opinion but @fabpot needs to decide in the end.

@arnaud-lb
Copy link
Contributor Author

@stof rebased

@alvarezmario
Copy link
Contributor

@fabpot Any final word about this pull request? It would be nice to have this feature ready for 2.1.

@asm89
Copy link
Contributor

asm89 commented Apr 24, 2012

Using the {_locale} placeholder in the host would set the locale for the request just like it does now?

Another thing I'm wondering is how/if it should be possible to set the hostname pattern for all your routes, or at least when importing routes? Otherwise you'll end up repeating the same host pattern over and over again. I think this is also important when importing routes from third party bundles.

@fabpot
Copy link
Member

fabpot commented Apr 25, 2012

I'm reviewing this PR and I'm going to make some modifications. I will send a PR to @arnaud-lb soon.

@fabpot
Copy link
Member

fabpot commented Apr 25, 2012

I've sent a PR to @arnaud-lb arnaud-lb#3 that fixes some minor bugs and add support in more classes.

@fabpot
Copy link
Member

fabpot commented Apr 25, 2012

@asm89:

Placeholders in the hostname are managed in the same way as the ones from the URL pattern.

You can set a hostname pattern for a collection (like the prefix for URL patterns).

@Tobion
Copy link
Contributor

Tobion commented Apr 25, 2012

I think we need to change the contents of $variables, $tokens, and $hostnameTokens in the CompiledRoute. They contain redundant information and the content structure of these variables ist not documentation in any way. If we remove duplicated content and put it in a (single) well defined variable, it would also reduce the information that need to be saved in the generated class by the UrlGeneratorDumper.

$this->addRoute($route);
return $this;

} else if ('' === $this->getPrefix() || 0 === strpos($prefix, $this->getPrefix())) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need for elseif, previous statement returns

@fabpot
Copy link
Member

fabpot commented Nov 12, 2012

@wendigo But there is one thing that would definitely be helpful: try to use this feature in your code and give us some feedback.

@Tobion
Copy link
Contributor

Tobion commented Nov 12, 2012

@fabpot: It's the discussion on on outdated diff at 2012-11-11T06:56:27-08:00

@Tobion
Copy link
Contributor

Tobion commented Nov 12, 2012

@fabpot now it's ready to be merged.

@userfriendly
Copy link
Contributor

Awesome. This is like Christmas if Santa brought code instead of presents.

@Seldaek
Copy link
Member

Seldaek commented Nov 12, 2012

Not sure if the sample at the top is up to date (didn't read the gazillion comments) but can I ask why hostname_pattern vs just hostname or even better _hostname in requirements? It just seems a bit weirdly inconsistent, but maybe there is a good reason I missed.

@arnaud-lb
Copy link
Contributor Author

@Seldaek the hostname pattern allows {placeholders}, which work exactly like the pattern's placeholders, can have requirements too, etc. I though hostname_pattern would make it more obvious that it works like pattern, but for the hostname.

@Seldaek
Copy link
Member

Seldaek commented Nov 12, 2012

I see, then I agree it might not belong in requirements, but still not sure hostname vs hostname_pattern.. The _pattern surely didn't hint at anything for me, but maybe that's my bad :)

@Tobion
Copy link
Contributor

Tobion commented Nov 12, 2012

I also raised this question. But since it's pattern for the path, I'm fine with the suffix in hostname_pattern for the host.
It's the best consistency we can get. Too bad, pattern is not named path or path_pattern. This would be much better, but I guess we cannot change it anymore. Or @fabpot, would you accept deprecating pattern in favor of path in 2.2? And removing it in 2.3 so we have a clean naming in LTS?

@fabpot
Copy link
Member

fabpot commented Nov 12, 2012

@Tobion: I've created an issue for the renaming: #5989

@alvarezmario
Copy link
Contributor

@fabpot Are you going to wait for the discussion on that issue before merging this?

fabpot added a commit that referenced this pull request Nov 12, 2012
This PR was merged into the master branch.

Commits
-------

17f51a1 Merge pull request #6 from Tobion/hostname-routes
e120a7a fix API of RouteCollection
26e5684 some type fixes
514e27a [Routing] fix PhpMatcherDumper that returned numeric-indexed params that are returned besides named placeholders by preg_match
7ed3013 switch to array_replace instead of array_merge
94ec653 removed irrelevant string case in XmlFileLoader
9ffe3de synchronize the fixtures in different formats and fix default for numeric requirement
6cd3457 fixed CS
8366b8a [Routing] fixed validity check for hostname params in UrlGenerator
a8ce621 [Routing] added support for hostname in the apache matcher dumper
562174a [Routing] fixed indentation of dumped collections
1489021 fixed CS
a270458 [Routing] added some more unit tests
153fcf2 [Routing] added some unit tests for the PHP loader
68da6ad [Routing] added support for hostname in the XML loader
3dfca47 [Routing] added some unit tests for the YAML loader
92f9c15 [Routing] changed CompiledRoute signature to be more consistent
d91e5a2 [Routing] fixed Route annotation for hostname (should be hostname_pattern instead of hostnamePattern)
62de881 [Routing] clarified a variable content
11b4378 [Routing] added hostname support in UrlMatcher
fc015d5 [Routing] fixed route generation with a hostname pattern when the hostname is the same as the current one (no need to force the generated URL to be absolute)
462999d [Routing] display hostname pattern in router:debug output
805806a [Routing] added hostname matching support to UrlGenerator
7a15e00 [Routing] added hostname matching support to AnnotationClassLoader
cab450c [Routing] added hostname matching support to YamlFileLoader
85d11af [Routing] added hostname matching support to PhpMatcherDumper
402359b [Routing] added hostname matching support to RouteCompiler
add3658 [Routing] added hostname matching support to Route and RouteCollection
23feb37 [Routing] added hostname matching support to CompiledRoute

Discussion
----------

[2.2][Routing] hostname pattern for routes

Bug fix: no
Feature addition: yes
Fixes the following tickets: #1762, #3276
Backwards compatibility break: no
Symfony2 tests pass: yes

This adds a hostname_pattern property to routes. It works like the pattern property (hostname_pattern can have variables, requirements, etc). The hostname_pattern property can be set on both routes and route collections.

Yaml example:

``` yaml
# Setting the hostname_pattern for a whole collection of routes

AcmeBundle:
    resource: "@AcmeBundle/Controller/"
    type: annotation
    prefix: /
    hostname_pattern: {locale}.example.com
    requirements:
        locale: en|fr

# Setting the hostname_pattern for single route

some_route:
    pattern: /hello/{name}
    hostname_pattern: {locale}.example.com
    requirements:
        locale: en|fr
        name: \w+
    defaults:
        _controller: Foo:bar:baz
```

Annotations example:

``` php
<?php

/**
 * Inherits requirements and hostname pattern from the collection
 * @route("/foo")
 */
public function fooAction();

/**
 * Set a specific hostnamePattern for this route only
 * @route("/foo", hostnamePattern="{_locale}.example.com", requirements={"_locale="fr|en"})
 */
public function fooAction();

```

Performance:

Consecutive routes with the same hostname pattern are grouped, and a single test is made against the hostname for this group, so the overhead is very low:

```
@route("/foo", hostnamePattern="a.example.com")
@route("/bar", hostnamePattern="a.example.com")
@route("/baz", hostnamePattern="b.example.com")
```

is compiled like this:

```
if (hostname matches a.example.com) {
    // test route "/foo"
    // test route "/bar"
}
if (hostname matches b.example.com) {
    // test route "/baz"
}
```

The PR also tries harder to optimize routes sharing the same prefix:

```
@route("/cafe")
@route("/cacao")
@route("/coca")
```

is compiled like this:

```
if (url starts with /c) {
    if (url starts with /ca) {
        // test route "/cafe"
        // test route "/cacao"
    }
    // test route "/coca"
}
```

---------------------------------------------------------------------------

by Koc at 2012-02-16T14:14:19Z

Interesting. Have you looked at #3057, #3002?

Killer feature of #3057 : multiple hostnames per route.

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-16T14:21:28Z

@Koc yes, the main difference is that this PR allows variables in the hostname pattern, with requirements, etc just like the path pattern. The other PRs use a `_host` requirement, which works like the `_method` requirement (takes a list of allowed hostnames separated by `|`).

> Killer feature of #3057 : multiple hostnames per route.

If you have multiple tlds you can easily do it like this:

``` yaml
hostbased_route:
  pattern:  /
  hostname_pattern: symfony.{tld}
  requirements:
     tld: org|com
```

Or with completely different domain names:

``` yaml
hostbased_route:
  pattern:  /
  hostname_pattern: {domain}
  requirements:
     domain: example\.com|symfony\.com
```

Requirements allow DIC %parameters%, so you can also put you domains in your config.yml.

---------------------------------------------------------------------------

by Koc at 2012-02-16T15:52:16Z

wow, nice! So looks like this PR closes my #3276 ticket?

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-16T15:53:55Z

Yes, apparently :)

---------------------------------------------------------------------------

by Koc at 2012-02-16T15:56:53Z

I cann't find method `ParameterBag::resolveValue` calling in this PR, like here https://github.com/symfony/symfony/pull/3316/files

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-16T16:03:48Z

I think it's in core already

---------------------------------------------------------------------------

by Koc at 2012-02-16T16:11:38Z

looks like yes
https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php#L81

---------------------------------------------------------------------------

by dlsniper at 2012-02-16T19:37:57Z

This PR looks great, it's something like this I've been waiting for.

I know @fabpot said he's working on something similar but I think if he agrees with this it could be a great addition to the core.

@fabpot , @stof any objections about this PR if gets fully done?

---------------------------------------------------------------------------

by stof at 2012-02-16T20:00:21Z

Well, we already have 2 other implementations for this stuff in the PRs. @fabpot please take time to look at them

---------------------------------------------------------------------------

by stof at 2012-02-16T20:03:17Z

This one is absolutely not tested and seems to break the existing tests according to the description. So it cannot be reviewed as is.

---------------------------------------------------------------------------

by dlsniper at 2012-02-16T22:00:24Z

@stof I understand it's a WIP but the other PRs where ignored as well and like you've said, there's a bunch of PRs already on this issue all doing a thing or another. So an early feedback on this, or any other, could lead it to the right path in order to finally solve this issue.

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-17T23:57:28Z

Added tests; others are passing now

---------------------------------------------------------------------------

by arnaud-lb at 2012-02-22T21:10:20Z

I'm going to add support for the Apache dumper and the XML loader; does this PR have a chance to be merged ? cc @fabpot @stof

---------------------------------------------------------------------------

by stof at 2012-02-22T22:05:23Z

@arnaud-lb We need to wait @fabpot's mind about the way he prefers to implement it to know which one can be merged.

---------------------------------------------------------------------------

by IjinPL at 2012-02-27T02:01:57Z

Forked @arnaud-lb *hostname_pattern* to add XML parasing support.

---------------------------------------------------------------------------

by stof at 2012-04-03T23:59:12Z

@arnaud-lb Please rebase your branch. It conflicts with master because of the move of the tests

@fabpot @vicb ping

---------------------------------------------------------------------------

by dlsniper at 2012-04-13T19:52:23Z

Hi,

If @arnaud-lb won't be able to rebase this I could help with some work on this but there's still the problem of actually choosing the right PR(s) for this issue. @blogsh says in his last commit that this PR is a bit better in his opinion but @fabpot needs to decide in the end.

---------------------------------------------------------------------------

by arnaud-lb at 2012-04-14T17:26:55Z

@stof rebased

---------------------------------------------------------------------------

by nomack84 at 2012-04-20T13:01:00Z

@fabpot Any final word about this pull request? It would be nice to have this feature ready for 2.1.

---------------------------------------------------------------------------

by asm89 at 2012-04-24T21:27:50Z

Using the `{_locale}` placeholder in the host would set the locale for the request just like it does now?

Another thing I'm wondering is how/if it should be possible to set the hostname pattern for all your routes, or at least when importing routes? Otherwise you'll end up repeating the same host pattern over and over again. I think this is also important when importing routes from third party bundles.

---------------------------------------------------------------------------

by fabpot at 2012-04-25T01:17:51Z

I'm reviewing this PR and I'm going to make some modifications. I will send a PR to @arnaud-lb soon.

---------------------------------------------------------------------------

by fabpot at 2012-04-25T03:10:18Z

I've sent a PR to @arnaud-lb arnaud-lb#3 that fixes some minor bugs and add support in more classes.

---------------------------------------------------------------------------

by fabpot at 2012-04-25T03:12:52Z

@asm89:

Placeholders in the hostname are managed in the same way as the ones from the URL pattern.

You can set a hostname pattern for a collection (like the prefix for URL patterns).

---------------------------------------------------------------------------

by Tobion at 2012-04-25T09:31:19Z

I think we need to change the contents of $variables, $tokens, and $hostnameTokens in the CompiledRoute. They contain redundant information and the content structure of these variables ist not documentation in any way. If we remove duplicated content and put it in a (single) well defined variable, it would also reduce the information that need to be saved in the generated class by the UrlGeneratorDumper.

---------------------------------------------------------------------------

by arnaud-lb at 2012-04-26T08:54:21Z

@fabpot thanks :) I've merged it

---------------------------------------------------------------------------

by stof at 2012-04-26T12:08:40Z

A rebase is needed

---------------------------------------------------------------------------

by fabpot at 2012-04-26T13:28:08Z

no need to rebase, I will resolve the conflicts when merging. I've still have some minor changes to do before merging though. Anyone willing to have a look at implementing the Apache dumper part?

---------------------------------------------------------------------------

by Tobion at 2012-04-26T14:59:00Z

@fabpot you want to merge this for 2.1 although it introduces big changes that need extensive review and testing? But #3958 is not considered for 2.1? I thought we are in some sort of feature freeze for the components in order to not postpone the release.

---------------------------------------------------------------------------

by fabpot at 2012-04-26T17:21:09Z

@Tobion: I never said it will be in 2.1. The plan is to create a 2.1 branch soon so that we can continue working on 2.2.

---------------------------------------------------------------------------

by Koc at 2012-04-26T19:46:43Z

https://twitter.com/#!/fabpot/status/178502663690915840
@fabpot fabpot merged commit 17f51a1 into symfony:master Nov 12, 2012
@fabpot
Copy link
Member

fabpot commented Nov 12, 2012

Merged! Thanks you very much to everyone who participated in this PR, especially @arnaud-lb and @Tobion.

Enjoy!

@arnaud-lb
Copy link
Contributor Author

Thanks!

@dlsniper
Copy link
Contributor

Thank you for this awesome feature @arnaud-lb @Tobion and everyone else!

@patie
Copy link
Contributor

patie commented Nov 12, 2012

THANKS!

@bitomule
Copy link

Any chance I can use this feature on symfony 2.1? I really need this feature and can't wait for 2.2.

I want to change this:

domain.com/username (my current route)

to:

username.domain.com (how I want routing to work)

Of course I've a wildcard on my dns so all the traffic from subdomains goes to the same server. That works.

Thanks!

@philipphoffmann
Copy link
Contributor

@bitomule: you can use apache redirects (RewriteCond and RewriteRule) in the mean time to get this accomplished

@bitomule
Copy link

I'm trying to use apache redirects, but that changes my browser url. This are my apache conditions and rules:

RewriteCond %{HTTP_HOST} !^www\.mydomain\.net$
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.net$

RewriteRule ^(.*)$ http://mydomain.net\/%1 [QSA,L]

Thanks!

@lushc
Copy link

lushc commented Jan 26, 2013

@bitomule: and this RewriteRule isn't being matched?

@philipphoffmann
Copy link
Contributor

try something like this:

RewriteCond %{HTTP_HOST} (.+)\.domain\.com
RewriteRule ^(.+)$ /%1/$1 [L]

@bitomule
Copy link

The RewriteRule is matched, but it changes browser url, I don't want that url to change.

@philipphoffmann , yours doesn't even work :(

@philipphoffmann
Copy link
Contributor

try replacing the + in RewriteRule with *****, like this:

RewriteRule ^(.*)$ /%1/$1 [L]

@lazyhammer
Copy link
Contributor

@bitomule , you're making rewrite to an absolute URL with another hostname, that's why Apache performs an external redirect. To avoid this, use an URL-path, or try the proxy flag:

RewriteCond %{HTTP_HOST} ^([^\.]++)\.mydomain\.net$
RewriteCond %1 !=www
RewriteRule .* /%1/$0 [QSA,L]
# or
# RewriteRule .* http://mydomain.net/%1/$0 [QSA,P]

@bitomule
Copy link

Thanks for all your help, but it doesn't work :(

I've tryed @philipphoffmann version and both @lazyhammer options so maybe my problem is in other part of the virtual host, so I paste the full virtualhost configuration.

This is my virtualhost configuration, the one that works but changes url:

<VirtualHost *:80>
ServerName mydomain.net
ServerAlias *.mydomain.net

DocumentRoot /var/www/prod/web
ServerAdmin webmaster@mydomain.com

<Directory "/var/www/prod/web">
   DirectoryIndex app.php
   AllowOverride All
   Order allow,deny
   Allow from all
   RewriteEngine On

   #Remove final slash
RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301]


  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !^/(media|skin|js|css)/
  RewriteCond %{HTTP_HOST} !^www\.mydomain\.net$
  RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.net$

  RewriteRule ^(.*)$ http://mydomain.net\/%1 [QSA,L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ app.php [QSA,L]
  RedirectMatch permanent ^/app\.php/(.*) /$1

</Directory>

@bitomule
Copy link

I'm finally waiting for symfony 2.2. When would symfony 2.2 be released? How can I update to beta? Should I?

Thanks!

@xarem
Copy link

xarem commented Feb 12, 2013

Is there a plan to use the hostname in the Symfony2 Firewall (security.yml)?

Example:

security:
    firewalls:
        example:
          pattern: ^/example
          host: ^user.example.com$

@bitomule: Symfony 2.2 will be released at the end of February 2013 (http://symfony.com/doc/current/contributing/community/releases.html#schedule). Update your requirements in the composer.json to 2.2 and run composer update to upgrade (see: https://github.com/symfony/symfony-standard/blob/master/composer.json)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.