четверг, 31 января 2013 г.

Установка The Bug Genie на Centos, баг с mod_rewrite - и попытки разложить все грабли по... комментариям к посту

Не было разрешено по умолчанию использование .htaccess, не сработал модуль mod_rewrite, так пришлось "вспоминать" httpd.conf ... В комментариях есть даже процесс установки ThebugGenie... В меню (и комментариях) есть ссылки на переводы конфиг. файлов из моего ноутбука... Чтобы исправить ошибку я поменял в &lh;Directory "/var/www/html"> строчку "AllowOverride None" на "AllowOverride All"... всего и делов то..., но...
Возникает вопрос, насколько уменьшится скорость обработки запросов, если сервер будет искать во всех директориях .htaccess ?
Наверное, лучшим стилем следует считать разрешения не для всех папок html, а только для подпапки thebuggenie, например...
Drupal то ведь работал при отключенных .htaccess ...
А еще более "правильным" представляется вариант, где вместо .htaccess все директивы для модуля mod_rewrite прописаны в отдельной секции (Virtual host, например) основоного файла httpd.conf
Но в этом посте я изначально хотел описапть процесс установки. Что и сделал довольно подробно, если учесть копипаст сообщений скрипта установки в комментариях. Более подробые варианты настроек можно найти на Хабре...
#

/etc/httpd - здесь
Документы и ответы на вопросы в комментариях надо начинать искать здесь:
/usr/share/doc/httpd-2.2.23
/usr/share/doc/php-common-5.3.20
/usr/share/phpmyadmin - это дистрибутив

/usr/share/php - а это только папка пустая (!)
/etc/php.ini - здесь можно найти все остальные пути...

/selinux - а эта папка в корне (!)
/etc/selinux
0. Скачал дистрибутив с сайта (клик по картинке) распаковал и сохранил на рабочем столе.
1.Залил дистрибутив в var/www/html/thebuggenie, делал это командой
cp -R
дабы SELinux сразу выдал бы контекст для httpd..., если дистрибутив передвинуть командой mv, то останется контекст директории закачки/распаковки (у меня - Desktop).
3. Открыл в браузере localhost/thebuggenie, оказалось, что скрипт установки надо запускать из localhost/thebuggenie/thebuggenie/index.php
Сразу выскочила ошибка: make thebuggenie/core/cache writable, хозяино директории был пользователь root, пришлось выдать 777 (использовал не строку bash, а файл менеджер).
После этого процесс установки пошел... и я решил скопировать его в комментарии. Как видно из второго комментария, было предложено поменять разрешения еще для нескольких директорий, что и было сделано.
Далее (31 января) скрипт установки несколько раз предупредил меня о настройках modrewrite - можно это было сделать в секции virtual host (в основном конфигурационном файле), а можно было и в .htaccess
Но....Получилось так, что после установки я окрыл страничку установленного сайта, а там CSS не работает... время было позднее, потому выключил я тогда компьютер, а к установке вернулсь только три дня спустя...
1.Я при установке не обратил внимания на эти предупреждения... и не проверил в конце концов AllowOverride (у меня стояло None в httpd.conf).
2. Далее, вместо того, чтобы перечитать свои же записи, я попытался найти описание бага установки на сайте thebuggenie. Нашел несколько, там упоминался модуль modrewrite.... Я удостоверился, что модуль подключен (httpd.conf) и запущен (.htaccess), перечитал книжки про настройки httpd.conf, php.ini, наконец, нагуглил статьи по modrewrite и...
3. "Вспомнил" процесс обработки запроса сервером... (это надо было сделать в первую очередь, а я искал "методом тыка"... )
4. В итоге, я "вспомнил" многие директивы из (httpd.conf, php.ini) и процесс обработки запроса сервером, что само по себе полезно... но

Другие посты по настройкам Apache

28 комментариев:

  1. Mozilla Public License 1.1 accepted ...
    iconsets/oxygen/action_ok.pngPHP version (5.3.20) meets requirements ...
    iconsets/oxygen/action_ok.pngPCRE librairies version (8.31 2012-07-06) meets requirements ...
    iconsets/oxygen/action_ok.pngPHP docblocks are readable ...
    Could not write to The Bug Genie directory
    The main folder for The Bug Genie should be writable during installation, since we need to store some information in it
    If you're installing this on a Linux server, running this command should fix it:
    chmod a+w /var/www/html/thebuggenie/
    iconsets/oxygen/action_ok.pngCan write to /var/www/html/thebuggenie/core/cache and /var/www/html/thebuggenie/core/cache/B2DB
    Could not write to The Bug Genie public directory
    The public folder for The Bug Genie should be writable during installation, since we need to store some information in it
    If you're installing this on a Linux server, running this command should fix it:
    chmod a+w /var/www/html/thebuggenie/thebuggenie/
    iconsets/oxygen/action_ok.pngPHP extension mbstring is loaded
    iconsets/oxygen/action_ok.pngPHP PDO installed and enabled ...
    iconsets/oxygen/action_ok.pngPHP PDO MySQL installed and enabled ...
    PDO PostgreSQL driver not enabled
    You won't be able to install The Bug Genie on a PostgreSQL database.
    More information is available at php.net
    Could not write the SQL settings file
    The folder that contains the SQL settings is not writable
    If you're installing this on a Linux server, running those commands should fix it:
    touch /var/www/html/thebuggenie/core/b2db_bootstrap.inc.php
    chmod a+w /var/www/html/thebuggenie/core/b2db_bootstrap.inc.php
    iconsets/oxygen/action_ok.pngCan save database connection details ...
    iconsets/oxygen/action_ok.pngPHP GD library installed and enabled ...

    ОтветитьУдалить
    Ответы
    1. Все выполнил, как и было предписано
      [root@localhost ~]# cd /
      [root@localhost /]# chmod a+w /var/www/html/thebuggenie/

      [root@localhost /]# chmod a+w /var/www/html/thebuggenie/thebuggenie/

      [root@localhost /]# touch /var/www/html/thebuggenie/core/b2db_bootstrap.inc.php
      [root@localhost /]# chmod a+w /var/www/html/thebuggenie/core/b2db_bootstrap.inc.php

      Удалить
  2. Pre-installation checks

    Before we can start the installation, we need to check a few things.
    Please look through the list of prerequisites below, and take the necessary steps to correct any errors that may have been highlighted.
    iconsets/oxygen/action_ok.pngMozilla Public License 1.1 accepted ...
    iconsets/oxygen/action_ok.pngPHP version (5.3.20) meets requirements ...
    iconsets/oxygen/action_ok.pngPCRE librairies version (8.31 2012-07-06) meets requirements ...
    iconsets/oxygen/action_ok.pngPHP docblocks are readable ...
    iconsets/oxygen/action_ok.pngCan write to The Bug Genie directory ...
    iconsets/oxygen/action_ok.pngCan write to /var/www/html/thebuggenie/core/cache and /var/www/html/thebuggenie/core/cache/B2DB
    iconsets/oxygen/action_ok.pngCan write to The Bug Genie public directory ...
    iconsets/oxygen/action_ok.pngPHP extension mbstring is loaded
    iconsets/oxygen/action_ok.pngPHP PDO installed and enabled ...
    iconsets/oxygen/action_ok.pngPHP PDO MySQL installed and enabled ...

    PDO PostgreSQL driver not enabled
    You won't be able to install The Bug Genie on a PostgreSQL database.
    More information is available at php.net

    iconsets/oxygen/action_ok.pngCan save database connection details ...
    iconsets/oxygen/action_ok.pngPHP GD library installed and enabled ...

    ОтветитьУдалить
    Ответы
    1. Ну и ладно,
      PDO PostgreSQL driver not enabled
      You won't be able to install The Bug Genie on a PostgreSQL database.
      More information is available at php.net

      не очень то и хотелось...

      Удалить
  3. Database information

    The Bug Genie uses a database to store information. To be able to connect to - and store information in - your database, we need some connection information.
    First of all, we need the database username and password:
    1: Username, password and table prefix

    Username
    The username used to connect to the database
    Password
    The password used to connect to the database
    Table prefix
    The table prefix used for all database tables

    Now, please fill in the connection information:
    DSN Custom
    2: Connection information

    Type
    What kind of database The Bug Genie will connect to
    Hostname
    The hostname of the database The Bug Genie should connect to
    Port number
    The port number for the database The Bug Genie should connect to
    Database name
    The database used to store the bug genie tables (must already exist!)

    ОтветитьУдалить
    Ответы
    1. All tables were created successfully, and the database connection details have been saved
      If you need to restart the installation, you won't have to enter these details again

      Удалить
    2. Server / URL information
      The Bug Genie uses URL rewriting to make URLs look more readable. URL rewriting is what makes it possible to, instead of viewissue.php?project_key=projectname&issue_id=123, use URLs such as /projectname/issue/123.

      It is important that The Bug Genie and your web server is correctly set up with url rewriting enabled for this to work.

      You can read more about setting up URL rewriting, here:
      http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html (Apache)
      http://support.microsoft.com/kb/324000/ (IIS)

      For Apache, it is enough that the rewrite module (mod_rewrite) is installed and enabled, and that the virtual host setup has set AllowOverride All for the folder The Bug Genie is located.
      With this setup, Apache should use the .htaccess file located inside the thebuggenie/ folder.

      If you for any reason cannot turn on AllowOverride All for that folder, look at the .htaccess file The Bug Genie bundles (located inside the thebuggenie/ folder, and copy the necessary lines to your virtual host definition.

      Удалить
  4. EXAMPLE #1: The Bug Genie is installed in /var/www/thebuggenie, and I want to set up a virtual host for The Bug Genie.
    Apache setup: Set up the virtual host as usual, but point the DocumentRoot for The Bug Genie to the thebuggenie/ subfolder inside the main folder. Make sure the apache virtual host setup has AllowOverride All for the folder where The Bug Genie is located, and make sure the .htaccess file inside the thebuggenie/-folder is accessible to Apache.

    The Bug Genie setup: With this setup, The Bug Genie will be located at the top level, so set the URL subdirectory below to "/", which means "top level".

    ОтветитьУдалить
  5. EXAMPLE #2: The Bug Genie is installed in /var/www/thebuggenie, and I want to access it as a subfolder of the DocumentRoot, which is /var/www
    Apache setup: Make sure the apache host setup has AllowOverride All for the folder thebuggenie is located, and make sure the .htaccess file inside the thebuggenie/-folder is accessible to Apache. You may want to copy the main folder content to a folder one level up (extract the main content of the top thebuggenie/-folder directly to /var/www), so that the thebuggenie/-folder inside the main folder is accessible as /var/www/thebuggenie.

    The Bug Genie setup: With this setup, The Bug Genie will be located at either http://hostname/thebuggenie/thebuggenie/ or http://hostname/thebuggenie/ (see above), so set the URL subdirectory below to match the subdirectory part (either "/thebuggenie/" or "/thebuggenie/thebuggenie/").
    See more information and examples at www.thebuggenie.com

    ОтветитьУдалить
  6. The Bug Genie URL information

    Set up my .htaccess file automatically Select "yes" if you are using an Apache web server
    Yes No
    Url subdirectory The part from the server root url to The Bug Genie
    According to the information above, The Bug Genie will be accessible at
    The Bug Genie will be available from other hostnames as well, but the subfolder path needs to be the same

    ОтветитьУдалить
  7. Apache .htaccess auto-setup completed successfully
    All settings were stored. Default data and settings loaded successfully
    Enabling functionality
    The Bug Genie consists of the Caspar framework, and a set of modules. These provide extra functionality such as VCS (version control system) integration and email communication.

    Please select which modules to enable here, before pressing "Continue":
    (You can always enable / disable this functionality from the configuration center after the installation is completed)
    The Bug Genie modules

    Enable email communication
    Enables functionality that sends and receives emails
    Yes No
    Enable VCS Integration
    Allows communication between VCS systems (such as svn) and The Bug Genie
    Yes No

    ОтветитьУдалить
  8. Please read the following information:
    Administrator account
    An administrator account has been created. To use this account, log in with the following information:
    Username: administrator
    Password: admin

    You should change this password immediately after finalizing the installation.
    This can be done from the "Account" page, available from the dropdown-menu in the top-right corner.

    ОтветитьУдалить
  9. Supporting further development
    Please remember: The Bug Genie is free / open source software, provided to you free of charge and developed by a small group of people. If this software proves valuable to you, please consider giving back. More information can be found here:
    http://thebuggenie.com/support (opens in a new window)
    Thank you for installing The Bug Genie!
    The Bug Genie builds upon its own open source php framework, and an open source PHP database layer called B2DB. If you find any bugs or issues, please use our issue tracker or send an email to support@thebuggenie.com.

    Help and support
    Online documentation is available from www.thebuggenie.com -> support. If you need more help, you can use the forums where there are a lot of helpful people around.
    Commercial email support is available for anyone with a support contract. For other inquiries, send an email to support@thebuggenie.com.

    ОтветитьУдалить
  10. При попытке открыть http://localhost/myphpadmin/
    в прошлый раз набрал http://localhost/phpmyadmin/, и задал неверный пароль...
    После этого не мог понять, как в Firefox убрать редирект на страницу ошибки ошибки ввода пароля...
    Стер куки домена localhost, не помогло, потом отключил javascript и ....забыл об этом
    Пароль узнал из файла установки Drupal, а в настроики (в фал /etc/httpd/conf.d/phpmyadmin.conf) добавил алиас (четвертая строка)
    Alias /phpmyadmin /usr/share/phpmyadmin
    Alias /phpMyAdmin /usr/share/phpmyadmin
    Alias /mysqladmin /usr/share/phpmyadmin
    Alias /myphpadmin /usr/share/phpmyadmin
    чтобы можно было набирать любой адрес (я почему то предпочитаю начинать с my, а не php)
    А сегодня (после пары дней перерыва ) снова набираю в строке браузера http://localhost/myphpadmin/
    и получаю страницу, исписанную одной и той же строчкой:
    Deprecated: Function eregi() is deprecated in /usr/share/phpmyadmin/libraries/select_lang.lib.php on line 146
    Оказалось, что дело в том, что в браузере отключена поддержка javascript, причем узнал об этом, когда решил войти в свой аккаунт (почту Гугл загрузить без явыскрипт, поскольку у вас отключена эта фича...)
    Даааа, "Function eregi() is deprecated..." ...??? ...без поллитры не разберешься, так выпьем же за ...кибернетика...

    ОтветитьУдалить
  11. А на чем я вообще остановился прошлый раз?
    Я пришел к выводу, что дело в скорее всего в том, что у меня не включен модуль mod_rewrite.
    1. Управлять им можно из нескольких мест (из старой книги Apache, потому надо проверить):
    1.1 httpd.conf - (сервер-конфигурация ) нашел строчки
    LoadModule rewrite_module modules/mod_rewrite.so
    1.2 .htaccess

    ОтветитьУдалить
    Ответы
    1. Уточняем, что есть в httpd.conf
      в разделе
      #
      # Dynamic Shared Object (DSO) Support
      #
      # To be able to use the functionality of a module which was built as a DSO you
      # have to place corresponding `LoadModule' lines at this location so the
      # directives contained in it are actually available _before_ they are used.
      # Statically compiled modules (those listed by `httpd -l') do not need
      # to be loaded here.
      .........
      LoadModule rewrite_module modules/mod_rewrite.so
      ............

      Удалить
    2. а вот
      # .htaccess file for The Bug Genie

      # make sure that magic_quotes and register_globals is always off

      php_flag magic_quotes_gpc off
      php_flag register_globals off


      # rewrite rules

      RewriteEngine On
      RewriteBase /thebuggenie/thebuggenie/
      # Example:
      # RewriteBase /
      # or
      # RewriteBase /dev/thebuggenie

      # skip all hidden files (starting with a .)
      RewriteCond %{REQUEST_URI} \..+$
      RewriteCond %{REQUEST_URI} !\.(html|wsdl|json|xml)$
      RewriteRule .* - [L]

      # redirect to front controller
      RewriteRule ^(.*)$ index.php?url=$1 [NC,QSA,L]



      # Stop people accessing directories they shouldn't have access to
      RedirectMatch 403 ^/\.svn(/|$)

      Удалить
    3. Надо разобраться с разрешениями, везде нужнв права суперпользователя root
      Может быть, дел в этом?
      Другой варинат -SELinux (надо просто отключить и посмотреть..., есть ли проблемы)

      Удалить


  12. #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important. Please see
    # http://httpd.apache.org/docs/2.2/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    # Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all


    ОтветитьУдалить
    Ответы
    1. Выше фрагмент из etc/httpd.conf
      Здесь, для директории &lh;Directory "/var/www/html"&gt: (blogspot вычистил подозрительные теги &lh;.....&gt: вместе с этой счтрокой, потому не понятно, что фактически)
      запрещено "переписывать" настройки etc/httpd.conf из файла .htaccess
      AllowOverride None
      Вот здесь можно посмотреть файл полностью: ranslate.google.com/toolkit/workbench?did=00egyvm007rua7tr7qbk&hl=ru
      А в комментарии ниже приведен тот же фрагмент файла из XAMPP Windows
      http://translate.google.com/toolkit/workbench?did=007hn59007rnnf43gnwg&hl=ru

      Удалить
    2. &lth;Directory "E:/xampp/htdocs">
      #
      # Possible values for the Options directive are "None", "All",
      # or any combination of:
      # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
      #
      # Note that "MultiViews" must be named *explicitly* --- "Options All"
      # doesn't give it to you.
      #
      # The Options directive is both complicated and important. Please see
      # http://httpd.apache.org/docs/2.2/mod/core.html#options
      # for more information.
      #
      Options Indexes FollowSymLinks Includes ExecCGI

      #
      # AllowOverride controls what directives may be placed in .htaccess files.
      # It can be "All", "None", or any combination of the keywords:
      # Options FileInfo AuthConfig Limit
      #
      AllowOverride All

      #
      # Controls who can get stuff from this server.
      #
      Require all granted

      </Directory&gth;

      Удалить
    3. Возникает частный вопрос, насколько уменьшится скорость обработки запросов, если сервер будет искать во всех директориях .htaccess ?

      Наверное, хорошим стилем следует считать разрешения не для всех папок html, а для thebuggenii, например...
      Drupal то ведь работал при отключенных .htaccess

      Кромет того, насколько я помню, просматриваются все вложенные папки... на предемет поиска .htaccess, таким образом, при любом редиректе modrewrite apache будет терять время...

      Удалить
    4. Вызывает вопрос и сравнение настроек
      Controls who can get stuff from this server.
      #
      Require all granted

      Вообще, насколько настройки XAMPP применимы для "боевого сервера"? Полагаю, что не очень применимы... Но настройки у меня на сервере еще "опаснее"?
      Где найти образец?

      Удалить
  13. Ну вот, разрешил использовать .htaccess
    Для этого в etc/httpd.conf для директории &lth;Directory "/var/www/html"> разрешил

    AllowOverride All

    И ГенийОшибок запустился. Посмотрел в директории Commons (Drupal), там .htaccess куда больше, но функции у него в основном декоративные... (если переделка URL и включена, то как? надо повнимательнее посмотреть...
    Пока вопрос с доступом остается открытым, надо не -забыть описать в посте процесс (есть в ссылках на modrewrite) j отработки сервером запроса. Там ведь еще и кэширование должно быть...
    Кроме того, как получить справку по опциям modrewrite? В PHP есть опция для справки по модулям, а в apache не нашел..

    ОтветитьУдалить
  14. Вот здесь, полагаю, можно найти ответы на все вопросы (скорость загрузки, безопасность...)
    http://habrahabr.ru/company/sprinthost/blog/129560/
    ....Первому RewriteRule передается путь от того места, где находится .htaccess, до запрошенного файла. Эта строка никогда не начинается со "/". Последующим RewriteRule передается результат предыдущих преобразований.

    Чтобы досконально понять, как работает RewriteRule, необходимо сначала определить, с чем он работает. Рассмотрим, как Apache получает строку, которая изначально передается на обработку RewriteRule в .htaccess.
    ....

    ОтветитьУдалить
    Ответы
    1. А здесь точно есть все ответы - 26 тописков, сотни комментариев
      http://habrahabr.ru/search/?q=[mod_rewrite]&target_type=posts

      Удалить
  15. http://habrahabr.ru/company/sprinthost/blog/129560/ (начал читать..., и не зря)
    Чтобы досконально понять, как работает RewriteRule, необходимо сначала определить, с чем он работает. Рассмотрим, как Apache получает строку, которая изначально передается на обработку RewriteRule в .htaccess.

    Когда только начинаешь работать с mod_rewrite, логично предполагаешь, что он работает со ссылками. Однако в случае с использованием mod_rewrite в .htaccess это не так. На самом деле в RewriteRule передается не ссылка, а путь до запрошенного файла.

    Из-за внутренней архитектуры Apache в тот момент, когда в действие вступает .htaccess, mod_rewrite может оперировать только с путем до файла, который должен быть обработан. Это связано с тем, что до передачи в mod_rewrite запрос уже могли изменить другие модули (например, mod_alias), и итоговый путь до файла на сайте уже может не совпадать с исходной ссылкой. Если бы mod_rewrite работал с исходной ссылкой, он бы нарушал действие модулей, которые изменили запрос до него.

    Поэтому в mod_rewrite передается абсолютный путь до файла, который должен быть обработан. Также mod_rewrite знает путь до .htaccess, в котором размещены правила RewriteRule. Чтобы сделать из пути до файла что-то похожее на ссылку, с которой планирует работать разработчик сайта, mod_rewrite отрезает от абсолютного пути часть до файла .htaccess.

    ОтветитьУдалить
  16. Разница в работе mod_rewrite в контексте .htaccess и в контексте VirtualHost

    В контексте mod_rewrite работает с точностью до наоборот.


    Как я говорил в начале статьи, все описанное выше касается применения mod_rewrite в контексте .htaccess. Если же mod_rewrite используется в , он будет работать по-другому:
    http://habrahabr.ru/company/sprinthost/blog/129560/
    В в RewriteRule попадает весь путь запроса, начиная от первого слеша, заканчивая началом параметров GET: «http://example.com/some/news/category/post.html?comments_page=3» -> "/news/category/post.html". Эта строка всегда начинается со /.
    Второй аргумент RewriteRule также необходимо начинать со /, иначе будет «Bad Request».
    RewriteBase не имеет смысла.
    Проход правил происходит только один раз. Флаг [L] действительно заканчивает обработку всех правил, описанных в , без каких-либо последующих итераций.

    ОтветитьУдалить