How to setup Apache-like name-based virtual hosts with Starman

佐手、 提交于 2019-12-05 01:18:36

问题


In my previous question I asked about a multi-domain solution, but the question was too complex.

Now in short:

Is it possible to somehow setup name-based virtual hosts with Starman (or with any other pure perl PSGI server) like with Apache's <VirtualHost ...> directive? Or do I need to use Apache to get this kind of functionality?

Any idea?


回答1:


The middleware is already done in Plack::Builder with Plack::App::URLMap. The pod saying:

Mapping URL with host names is also possible, and in that case the URL mapping works like a virtual host.

Syntax is in 3rd mount:

 builder {
      mount "/foo" => builder {
          enable "Plack::Middleware::Foo";
          $app;
      };

      mount "/bar" => $app2;
      mount "http://example.com/" => builder { $app3 };
  };



回答2:


Here the example: one module (App) for some sites.

Your lib/YourApp.pm should be as:

    package YourApp;

    use strict;
    use warnings;

    use Dancer ':syntax';

    setting apphandler => 'PSGI';

    Dancer::App->set_running_app('YourApp');

    # This and other routes ...
    get '/' => sub {
        # Static and template files will be from different directories are
        # based by host http header
        template 'index';
    };

    1;

Your bin/app.psgi should be as:

    #!/usr/bin/perl
    use strict;
    use warnings;

    use Dancer;

    # The next line can miss but need for quickly loading in L<Starman> server
    use YourApp;

    use Plack::Builder;

    # Please notice that here no need ports in url
    # So for http://app1.foo.com:3000/ will work
    # http://app1.foo.com/
    my $hosts = {
      'http://app1.foo.com/' => '/appdir/1',
      'http://app2.foo.com/' => '/appdir/2'
    };

    builder {
        my $last;
        foreach my $host (keys %$hosts) {
            $last = mount $host => sub {
                my $env = shift;
                local $ENV{DANCER_APPDIR} = $hosts->{$host};
                load_app "YourApp";
                Dancer::App->set_running_app('YourApp');
                setting appdir => $hosts->{$host};
                Dancer::Config->load;
                my $request = Dancer::Request->new( env => $env );
                Dancer->dance($request);
            };
         }
        $last;
    };

You can try a this my module - i think it will be more easy for virtual hosting than builder & mapping:

https://github.com/Perlover/Dancer-Plugin-Hosts



来源:https://stackoverflow.com/questions/6045399/how-to-setup-apache-like-name-based-virtual-hosts-with-starman

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!