Skip to content
This repository has been archived by the owner on Dec 30, 2023. It is now read-only.

Latest commit

 

History

History
489 lines (353 loc) · 20.9 KB

webserver-setup.md

File metadata and controls

489 lines (353 loc) · 20.9 KB
layout title keywords
default
Настройка веб-сервера
web server, webserver, apache, nginx, lighttpd, xampp, wamp, cherokee, php built-in server

Настройка веб-сервера


![](/assets/images/version-{{ pageVersion }}.svg)

Введение

Для работы приложения Phalcon вам нужно настроить ваш веб-сервер таким образом, чтобы он должным образом обрабатывал перенаправления. Ниже приведены инструкции для популярных веб-серверов:

Встроенный в PHP

The PHP built-in web server is not recommended for production applications. Тем не менее, его можно легко использовать в целях разработки. Способ запуска:

$(which php) -S <host>:<port> -t <directory> <setup file>

Если ваше приложение имеет точку входа в /public/index. hp или ваш проект был создан Phalcon Devtools, то вы можете запустить веб-сервер следующей командой:

$(which php) -S localhost:8000 -t public .htrouter.php

The above command does:

Command Описание
$(which php) will insert the absolute path to your PHP binary
-S localhost:8000 invokes server mode with the provided host:port
-t public defines the servers root directory, necessary for php to route requests to assets like JS, CSS, and images in your public directory
.htrouter.php the entry point that will be evaluated for each request

Файл .htrouter.php должен содержать:

<?php

declare(strict_types=1);

$uri = urldecode(
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

if ($uri !== '/' && file_exists(__DIR__ . '/public' . $uri)) {
    return false;
}

$_GET['_url'] = $_SERVER['REQUEST_URI'];

require_once __DIR__ . '/public/index.php';

Если ваша точка входа не public/index.php, то отредактируйте . trouter.php файл соответственно (последняя строка), а также вызов скрипта. Вы также можете изменить порт, если хотите, а также сетевой интерфейс, к которому он привязан.

After executing the command above, navigating to http://localhost:8000/ will show your site.

PHP-FPM

The PHP-FPM (FastCGI Process Manager) is usually used to allow the processing of PHP files. В настоящее время PHP-FPM комплектуется со всеми основанными на Linux дистрибутивами PHP.

On Windows PHP-FPM is in the PHP distribution archive. Файл php-cgi.exe может быть использован для запуска процесса и установки параметров. Windows не поддерживает unix сокеты, поэтому этот скрипт запустит fast-cgi в режиме TCP на 9000 порту.

Создайте файл php-fcgi.bat со следующим содержимым:

@ECHO OFF
ECHO Starting PHP FastCGI...
set PATH=C:\PHP;%PATH%
c:\bin\RunHiddenConsole.exe C:\PHP\php-cgi.exe -b 127.0.0.1:9000

nginx

nginx is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Unlike traditional servers, nginx doesn't rely on threads to handle requests. Instead, it uses a much more scalable event-driven (asynchronous) architecture. Эта архитектура под высокой нагрузкой использует небольшой, и главное, предсказуемый объем памяти.

Phalcon with nginx and PHP-FPM provide a powerful set of tools that offer maximum performance for your PHP applications.

Install nginx

nginx Official Site

Phalcon Configuration

You can use following potential configuration to set up nginx with Phalcon:

server {
    # Port 80 will require nginx to be started with root permissions
    # Depending on how you install nginx to use port 80 you will need
    # to start the server with `sudo` ports about 1000 do not require
    # root privileges
    # listen      80;

    listen        8000;
    server_name   default;

    ##########################
    # In production require SSL
    # listen 443 ssl default_server;

    # ssl on;
    # ssl_session_timeout  5m;
    # ssl_protocols  SSLv2 SSLv3 TLSv1;
    # ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    # ssl_prefer_server_ciphers   on;

    # These locations depend on where you store your certs
    # ssl_certificate        /var/nginx/certs/default.cert;
    # ssl_certificate_key    /var/nginx/certs/default.key;
    ##########################

    # This is the folder that index.php is in
    root /var/www/default/public;
    index index.php index.html index.htm;

    charset utf-8;
    client_max_body_size 100M;
    fastcgi_read_timeout 1800;

    # Represents the root of the domain
    # https://localhost:8000/[index.php]
    location / {
        # Matches URLS `$_GET['_url']`
        try_files $uri $uri/ /index.php?_url=$uri&$args;
    }

    # When the HTTP request does not match the above
    # and the file ends in .php
    location ~ [^/]\.php(/|$) {
        # try_files $uri =404;

        # Ubuntu and PHP7.0-fpm in socket mode
        # This path is dependent on the version of PHP install
        fastcgi_pass  unix:/var/run/php/php7.0-fpm.sock;


        # Alternatively you use PHP-FPM in TCP mode (Required on Windows)
        # You will need to configure FPM to listen on a standard port
        # https://www.nginx.com/resources/wiki/start/topics/examples/phpfastcgionwindows/
        # fastcgi_pass  127.0.0.1:9000;

        fastcgi_index /index.php;

        include fastcgi_params;
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        }

        fastcgi_param PATH_INFO       $fastcgi_path_info;
        # fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        # and set php.ini cgi.fix_pathinfo=0

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~ /\.ht {
        deny all;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires       max;
        log_not_found off;
        access_log    off;
    }
}

Start

Depending on your system, the command to start nginx could be one of the following:

start nginx
/etc/init.d/nginx start
service nginx start

Apache

Apache is a popular and well known web server available on many platforms.

Phalcon Configuration

The following are potential configurations you can use to set up Apache with Phalcon. Эти примеры в основном нацелены на настройку модуля mod_rewrite, позволяющего использовать понятные URL-адреса (ЧПУ) и компонента маршрутизации. Типичное приложение имеет следующую структуру:

tutorial/
  app/
    controllers/
    models/
    views/
  public/
    css/
    img/
    js/
    index.php

Document root The most common case is for an application to be installed in a directory under the document root. Если это так, то мы можем использовать .htaccess файлы. Во первых, он будет использоваться для скрытия кода приложения, пересылающего все запросы в корневой каталог приложения (public/).

NOTE: Note that using .htaccess files requires your apache installation to have the AllowOverride All option set.

{: .alert .alert-warning}

# tutorial/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule   ^$ public/    [L]
    RewriteRule   ((?s).*) public/$1 [L]
</IfModule>

Во вторых, файл .htaccess находящийся в каталоге public/, перезаписывает все URI в public/index.php файл:

# tutorial/public/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond   %{REQUEST_FILENAME} !-d
    RewriteCond   %{REQUEST_FILENAME} !-f
    RewriteRule   ^((?s).*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

International Characters For users that are using the Persian letter 'م' (meem) in uri parameters, there is an issue with mod_rewrite. Чтобы сопоставление работало как и с английскими символами, вам нужно изменить файл .htaccess:

# tutorial/public/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond   %{REQUEST_FILENAME} !-d
    RewriteCond   %{REQUEST_FILENAME} !-f
    RewriteRule   ^([0-9A-Za-z\x7f-\xff]*)$ index.php?params=$1 [L]
</IfModule>

Если URI вашего приложения может содержать символы, отличные от английского, вам, возможно, придется применить указанное выше изменение, чтобы результат работы модуля mod_rewrite точно соответствовал маршруту (роуту) приложения.

Apache Configuration

Если вы не хотите использовать файлы .htaccess, вы можете переместить соответствующие директивы в основной конфигурационный файл apache:

<IfModule mod_rewrite.c>

    <Directory "/var/www/test">
        RewriteEngine on
        RewriteRule  ^$ public/    [L]
        RewriteRule  ((?s).*) public/$1 [L]
    </Directory>

    <Directory "/var/www/tutorial/public">
        RewriteEngine On
        RewriteCond   %{REQUEST_FILENAME} !-d
        RewriteCond   %{REQUEST_FILENAME} !-f
        RewriteRule   ^((?s).*)$ index.php?_url=/$1 [QSA,L]
    </Directory>

</IfModule>

Виртуальные хосты

Конфигурация ниже предназначена для установки вашего приложения на виртуальном хосте:

<VirtualHost *:80>

    ServerAdmin    [email protected]
    DocumentRoot   "/var/vhosts/tutorial/public"
    DirectoryIndex index.php
    ServerName     example.host
    ServerAlias    www.example.host

    <Directory "/var/vhosts/tutorial/public">
        Options       All
        AllowOverride All
        Require       all granted
    </Directory>

</VirtualHost>

Lighttpd

lighttpd (pronounced "lighty") is an open-source web server optimized for speed-critical environments while remaining standards-compliant, secure and flexible. It was originally written by Jan Kneschke as a proof-of-concept of the c10k problem – how to handle 10,000 connections in parallel on one server, but has gained worldwide popularity. Its name is a portmanteau of "light" and "httpd".

Install lighttpd

lighttpd Official Site

You can use following potential configuration to set up lighttpd with Phalcon:

server.modules = (
        "mod_indexfile",
        "mod_access",
        "mod_alias",
        "mod_redirect",
        "mod_rewrite",
)

server.document-root        = "/var/www/html/public"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"
server.port                 = 80

# strict parsing and normalization of URL for consistency and security
# https://redmine.lighttpd.net/projects/lighttpd/wiki/Server_http-parseoptsDetails
# (might need to explicitly set "url-path-2f-decode" = "disable"
#  if a specific application is encoding URLs inside url-path)
server.http-parseopts = (
  "header-strict"           => "enable",# default
  "host-strict"             => "enable",# default
  "host-normalize"          => "enable",# default
  "url-normalize-unreserved"=> "enable",# recommended highly
  "url-normalize-required"  => "enable",# recommended
  "url-ctrls-reject"        => "enable",# recommended
  "url-path-2f-decode"      => "enable",# recommended highly (unless breaks app)
 #"url-path-2f-reject"      => "enable",
  "url-path-dotseg-remove"  => "enable",# recommended highly (unless breaks app)
 #"url-path-dotseg-reject"  => "enable",
 #"url-query-20-plus"       => "enable",# consistency in query string
)

index-file.names            = ( "index.php", "index.html" )
url.access-deny             = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "application/javascript", "text/css", "text/html", "text/plain" )

# default listening port for IPv6 falls back to the IPv4 port
include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
include_shell "/usr/share/lighttpd/create-mime.conf.pl"
include "/etc/lighttpd/conf-enabled/*.conf"

#server.compat-module-load   = "disable"
server.modules += (
        "mod_compress",
        "mod_dirlisting",
        "mod_staticfile",
)

url.rewrite-once = ( "^(/(?!(favicon.ico$|css/|js/|img/)).*)" => "/index.php?_url=$1" )
# or
#url.rewrite-if-not-file = ( "/" => "/index.php?_rl=$1" )

WAMP

WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP and a MySQL database. Below are detailed instructions on how to install Phalcon on WampServer for Windows. Using the latest WampServer version is highly recommended.

NOTE Paths in this guide should be relative, according to your installation WAMP

{: .alert .alert-warning }

Download Phalcon

For Phalcon to work on Windows, you must install the correct version that matches your architecture and extension built. Load up the phpinfo page provided by WAMP and check the Architecture and Extension Build values. Those will allow you to download the correct DLL. For a thread safe, x64 using VS16 and PHP 8.1, you will need to download the following file:

phalcon-php8.1-ts-windows2019-vs16-x64.zip

If your system reports NTS (Non Thread Safe) then you should download that DLL.

WAMP has both 32 and 64 bit versions. From the download section, you can download the Phalcon DLL that suits your WAMP installation.

Extract the php_phalcon.dll from the archive and copy the file php_phalcon.dll to the PHP extensions folder. If WAMP is installed in the C:\wamp folder, the extension needs to be in C:\wamp\bin\php\php8.1.0\ext (assuming your WAMP installation installed PHP 8.1.0).

Edit the php.ini file, it is located at C:\wamp\bin\php\php8.1.0\php.ini. It can be edited with Notepad or a similar program. We recommend Notepad++ to avoid issues with line endings. Append at the end of the file:

extension=php_phalcon.dll

and save it.

Also edit the php.ini file, which is located at C:\wamp\bin\apache\apache2.4.9\bin\php.ini. Append at the end of the file:

extension=php_phalcon.dll 

and save it.

NOTE: The path above might differ depending on the apache installation you have for your web server. Adjust it accordingly.

{: .alert .alert-warning }

Restart the Apache Web Server. Do a single click on the WampServer icon at system tray. Choose Restart All Services from the pop-up menu. Check out that tray icon will become green again.

Open your browser to navigate to https://localhost. The WAMP welcome page will appear. Check the section extensions loaded to ensure that Phalcon was loaded.

Congratulations! You are now phlying with Phalcon.

{: .alert .alert-info }

XAMPP

XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. Once you download XAMPP, all you have to do is extract it and start using it. Below are detailed instructions on how to install Phalcon on XAMPP for Windows. Using the latest XAMPP version is highly recommended.

NOTE Paths in this guide should be relative, according to your installation WAMP

{: .alert .alert-warning }

Download Phalcon

For Phalcon to work on Windows, you must install the correct version that matches your architecture and extension built. Load up the phpinfo page provided by WAMP and check the Architecture and Extension Build values. Those will allow you to download the correct DLL. For a thread safe, x64 using VS16 and PHP 8.1, you will need to download the following file:

phalcon-php8.1-ts-windows2019-vs16-x64.zip

If your system reports NTS (Non Thread Safe) then you should download that DLL.

XAMPP offers both 32 and 64 bit versions of Apache and PHP: Phalcon has dlls for both, just choose the right dll for the installed version.

Extract the php_phalcon.dll from the archive and copy the file php_phalcon.dll to the PHP extensions directory. If you have installed XAMPP in the C:\xampp folder, the extension needs to be in C:\xampp\php\ext

Edit the php.ini file, it is located at C:\wamp\bin\php\php8.1.0\php.ini. It can be edited with Notepad or a similar program. We recommend Notepad++ to avoid issues with line endings. Append at the end of the file:

extension=php_phalcon.dll

and save it.

Restart the Apache Web Server from the XAMPP Control Center. This will load the new PHP configuration. Open your browser to navigate to https://localhost. The XAMPP welcome page will appear. Click on the link phpinfo().

phpinfo will output a significant amount of information on screen about the current state of PHP. Scroll down to check if the Phalcon extension has been loaded correctly.

Congratulations! You are now phlying with Phalcon.

{: .alert .alert-info }

Cherokee

Cherokee is a high-performance web server. It is very fast, flexible and easy to configure.

Phalcon Configuration

Cherokee provides a friendly graphical interface to configure almost every setting available in the web server.

Start the cherokee administrator by executing as root /path-to-cherokee/sbin/cherokee-admin

Create a new virtual host by clicking on vServers, then add a new virtual server:

The recently added virtual server must appear at the left bar of the screen. In the Behaviors tab you will see a set of default behaviors for this virtual server. Click the Rule Management button. Remove those labeled as Directory /cherokee_themes and Directory /icons:

Add the PHP Language behavior using the wizard. This behavior allows you to run PHP applications:

Normally this behavior does not require additional settings. Add another behavior, this time in the Manual Configuration section. In Rule Type choose File Exists, then make sure the option Match any file is enabled:

In the Handler tab choose List & Send as handler:

Edit the Default behavior in order to enable the URL-rewrite engine. Change the handler to Redirection, then add the following regular expression to the engine ^(.*)$:

Finally, make sure the behaviors have the following order:

Execute the application in a browser: