Ubuntu 16.04 在 Apache2.4 用 mod_php 跑 PHP7.0

2017-02-09 Apache, Ubuntu

最近剛好在跑 Apache 2.4 + PHP7.0 順手記錄一下整個流程。

 

Apache 2.4 改進了很多設定方式 (i.e. a2ensite, a2dissite),和 Nginx 貼近不少更直覺了,效能也不錯,詳細看文件

PHP7.0 就不用說了,大幅改進效能問題,詳細看文件

 

然後因為工作環境的關係,之後開始會多用 Apache2.4。

 

安裝 Apache 2.4

名稱從 apache 改為 apache2,可見 Apache 把 2.2 和 2.4 想做一個區隔。

$ sudo apt-get install apache2 -y

 

安裝 PHP 7.0

名稱也是從 php 改為 php7.0,然後預設加上 php7.0-mysql 支援 mysql。

$ sudo apt-get install php7.0 php7.0-mysql libapache2-mod-php7.0 -y

 

設定 Apache 2.4

apache 2.4 目錄架構設計有 available and enabled 的區別,這點和 nginx 一樣,然後多了很多 a2ensite, a2dissite, a2enconf … etc 這類型的工具方便用來開啟設定 Apache。

$ sudo vim /etc/apache2/sites-available/site.com.tw.conf

<VirtualHost *:80>
  ServerName site.com.tw
  DocumentRoot /var/www/site
  DirectoryIndex index.php

  <Directory /var/www/site>
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>

  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

在 2.4 淘汰了 NameVirtualHost 的方式,採用和 Nginx 一樣用 ServerName 來指定 site,可以在 Upgrade 文件看到:

  • The NameVirtualHost directive no longer has any effect, other than to emit a warning. Any address/port combination appearing in multiple virtual hosts is implicitly treated as a name-based virtual host.

 

設定後要用 a2ensite 啟動並 reload

$ sudo a2ensite site.com.tw.conf
$ sudo systemctl restart apache2

 

印一個 phpinfo 來驗證

$ sudo vim /var/www/site/index.php

<?php
phpinfo();
?>

 

 

Troubleshooting

然後在某一台啟動 Apache 的時候出現這個錯誤:

Apache is running a threaded MPM, but your PHP Module is not compiled be threadsafe. You need recompile PHP.

因為在預設 apt-get 的 mod_php 是用 prefork MPM 編譯的,PHP 也在文件中提到就是不建議使用 threaded

 

Warning

We do not recommend using a threaded MPM in production with Apache 2. Use the prefork MPM, which is the default MPM with Apache 2.0 and 2.2. For information on why, read the related FAQ entry on usingApache2 with a threaded MPM

正常狀況在安裝 Apache 後預設是啟用 mpm_event,但是在安裝 libapache2_mod_php7.0 之後就會將 mpm_event 停用,啟用 mpm_prefork,如下:

Module mpm_event disabled.
Enabling module mpm_prefork.
apache2_switch_mpm Switch to prefork
apache2_invoke: Enable module php7.0
Setting up php7.0 (7.0.13-0ubuntu0.16.04.1) …

 

之後沒有直接求證為何沒有執行 mpm change mode 的動作,直接在下面寫解決方法:

$ sudo a2dismod mpm_event
$ sudo a2enmod mpm_prefork
$ sudo systemctl restart apache2

 

 

給 Mr. 沙先生一點建議

彙整

分類

展開全部 | 收合全部

License

訂閱 Mr. 沙先生 的文章

輸入你的 email 用於訂閱