1. 程式人生 > >Linux下PHP+Nginx環境搭建

Linux下PHP+Nginx環境搭建

PHP+Nginx環境搭建

作者:王宇陽( Mirror )^_^

參考文章:

​ Nginx+PHP+MySQL安裝參考

​ PHP原始碼安裝經驗

​ PHP原始碼環境搭建過程中常見問題

CentOS環境

配置CentOS-7網路:

CentOS(最小安裝)預設是不開啟網路的

  • 啟動網路

vi開啟:/etc/sysconfig/network-scripts/ifcfg-ens33 檔案

將 “ONBOOT:no”屬性修改為:“ONBOOT:yes”

  • 重啟網路服務
# sudo service network restart 
  • OK:
# ip addr

Nginx服務:

安裝依賴包

  • 安裝:

    # yum -y install build-essential
  • 安裝:更多依賴包

    # yum -y install gcc automake autoconf libtool make
  • 安裝:g++

    # yum -y install gcc gcc-c++

安裝PCRE庫

選定原始碼目錄 ==> ftp下載PCRE庫 ==> 安裝PCRE庫

# cd /usr/local/src

# wget ftp://ftp.pcre.org/pub/pcre/pcre-8.42.tar.gz

# tar -zxvf pcre-8.42.tar.gz

# cd /pcre-8.42

# ./configure

# make && make install

安裝zlib原始碼包

下載zlib原始碼包 ==> 安裝zlib包

# cd /usr/local/src

# wget http://zlib.net/zlib-1.2.11.tar.gz

# tar -zxvf zlib-1.2.11.tar.gz

# cd zlib-1.2.11

# ./configure

# make && make install

安裝openssl原始碼包

# cd /usr/local/src

# wget https://www.openssl.org/source/openssl-1.1.0k.tar.gz

# tar -zxvf openssl-1.1.0k.tar.gz

# cd ./openssl-1.1.0k

# ./configure

# make && make install

安裝Nginx

# cd /usr/local/src

# wget http://nginx.org/download/nginx-1.16.1.tar.gz

# tar -zxvf nginx-1.16.1.tar.gz

# cd nginx-1.16.1

# groupadd -r nginx
# useradd -r -g nginx nginx

# ./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/local/nginx/sbin/nginx \
--conf-path=/usr/local/nginx/nginx.conf \
--pid-path=/usr/local/nginx/nginx.pid \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_mp4_module  \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/tmp/nginx/client/ \
--http-proxy-temp-path=/var/tmp/nginx/proxy/ \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
--http-scgi-temp-path=/var/tmp/nginx/scgi \
--with-pcre=/usr/local/src/pcre-8.42 \
--with-zlib=/usr/local/src/zlib-1.2.11 \
--with-openssl=/usr/local/src/openssl-1.1.0k \

[注:當前所在目錄一定要是/usr/local/src/nginx-1.16.1

--with-pcre=/usr/local/src/pcre-8.41 指的是pcre-8.42 的原始碼路徑。

--with-zlib=/usr/local/src/zlib-1.2.11 指的是zlib-1.2.11 的原始碼路徑。

--with-openssl=/usr/local/src/openssl-1.1.0g 指的是openssl-1.1.0k 的原始碼路徑。]

# make && make install

nginx編譯選項

make是用來編譯的,它從Makefile中讀取指令,然後編譯。

make install是用來安裝的,它也從Makefile中讀取指令,安裝到指定的位置。

configure命令是用來檢測你的安裝平臺的目標特徵的。它定義了系統的各個方面,包括nginx的被允許使用的連線處理的方法,比如它會檢測你是不是有CC或GCC,並不是需要CC或GCC,它是個shell指令碼,執行結束時,它會建立一個Makefile檔案。nginx的configure命令支援以下引數:

  • --prefix=*path* 定義一個目錄,存放伺服器上的檔案 ,也就是nginx的安裝目錄。預設使用 /usr/local/nginx。
  • --sbin-path=*path* 設定nginx的可執行檔案的路徑,預設為 *prefix*/sbin/nginx.
  • --conf-path=*path* 設定在nginx.conf配置檔案的路徑。nginx允許使用不同的配置檔案啟動,通過命令列中的-c選項。預設為*prefix*/conf/nginx.conf.
  • --pid-path=*path* 設定nginx.pid檔案,將儲存的主程序的程序號。安裝完成後,可以隨時改變的檔名 , 在nginx.conf配置檔案中使用 PID指令。預設情況下,檔名 為``*prefix*/logs/nginx.pid.
  • --error-log-path=*path* 設定主錯誤,警告,和診斷檔案的名稱。安裝完成後,可以隨時改變的檔名 ,在nginx.conf配置檔案中 使用 的error_log指令。預設情況下,檔名 為*prefix*/logs/error.log.
  • --http-log-path=*path* 設定主請求的HTTP伺服器的日誌檔案的名稱。安裝完成後,可以隨時改變的檔名 ,在nginx.conf配置檔案中 使用 的access_log指令。預設情況下,檔名 為*prefix*/logs/access.log.
  • --user=*name* 設定nginx工作程序的使用者。安裝完成後,可以隨時更改的名稱在nginx.conf配置檔案中 使用的 user指令。預設的使用者名稱是nobody。
  • --group=*name* 設定nginx工作程序的使用者組。安裝完成後,可以隨時更改的名稱在nginx.conf配置檔案中 使用的 user指令。預設的為非特權使用者。
  • --with-select_module --without-select_module 啟用或禁用構建一個模組來允許伺服器使用select()方法。該模組將自動建立,如果平臺不支援的kqueue,epoll,rtsig或/dev/poll。
  • --with-poll_module --without-poll_module 啟用或禁用構建一個模組來允許伺服器使用poll()方法。該模組將自動建立,如果平臺不支援的kqueue,epoll,rtsig或/dev/poll。
  • --without-http_gzip_module — 不編譯壓縮的HTTP伺服器的響應模組。編譯並執行此模組需要zlib庫。
  • --without-http_rewrite_module 不編譯重寫模組。編譯並執行此模組需要PCRE庫支援。
  • --without-http_proxy_module — 不編譯http_proxy模組。
  • --with-http_ssl_module — 使用https協議模組。預設情況下,該模組沒有被構建。建立並執行此模組的OpenSSL庫是必需的。
  • --with-pcre=*path* — 設定PCRE庫的原始碼路徑。PCRE庫的原始碼(版本4.4 - 8.30)需要從PCRE網站下載並解壓。其餘的工作是Nginx的./ configure和make來完成。正則表示式使用在location指令和 ngx_http_rewrite_module 模組中。
  • --with-pcre-jit —編譯PCRE包含“just-in-time compilation”(1.1.12中, pcre_jit指令)。
  • --with-zlib=*path* —設定的zlib庫的原始碼路徑。要下載從 zlib(版本1.1.3 - 1.2.5)的並解壓。其餘的工作是Nginx的./ configure和make完成。ngx_http_gzip_module模組需要使用zlib 。
  • --with-cc-opt=*parameters* — 設定額外的引數將被新增到CFLAGS變數。例如,當你在FreeBSD上使用PCRE庫時需要使用:--with-cc-opt="-I /usr/local/include。.如需要需要增加 select()支援的檔案數量:--with-cc-opt="-D FD_SETSIZE=2048".
  • --with-ld-opt=*parameters* —設定附加的引數,將用於在連結期間。例如,當在FreeBSD下使用該系統的PCRE庫,應指定:--with-ld-opt="-L /usr/local/lib".

安裝完成後,按照安裝的引數,安裝的啟動目錄在/usr/local/nginx

[root@localhost nginx]# ls -l
總用量 76
drwxr-xr-x. 2 root root 4096 9月   8 09:46 conf
-rw-r--r--. 1 root root 1077 9月   8 10:34 fastcgi.conf
-rw-r--r--. 1 root root 1077 9月   8 10:34 fastcgi.conf.default
-rw-r--r--. 1 root root 1007 9月   8 10:34 fastcgi_params
-rw-r--r--. 1 root root 1007 9月   8 10:34 fastcgi_params.default
drwxr-xr-x. 2 root root   40 9月   8 09:46 html
-rw-r--r--. 1 root root 2837 9月   8 10:34 koi-utf
-rw-r--r--. 1 root root 2223 9月   8 10:34 koi-win
drwxr-xr-x. 2 root root   41 9月   8 10:37 logs
-rw-r--r--. 1 root root 5231 9月   8 10:34 mime.types
-rw-r--r--. 1 root root 5231 9月   8 10:34 mime.types.default
-rw-r--r--. 1 root root 2656 9月   8 10:34 nginx.conf
-rw-r--r--. 1 root root 2656 9月   8 10:34 nginx.conf.default
-rw-r--r--. 1 root root    6 9月   8 10:37 nginx.pid
drwxr-xr-x. 2 root root   36 9月   8 10:34 sbin
-rw-r--r--. 1 root root  636 9月   8 10:34 scgi_params
-rw-r--r--. 1 root root  636 9月   8 10:34 scgi_params.default
-rw-r--r--. 1 root root  664 9月   8 10:34 uwsgi_params
-rw-r--r--. 1 root root  664 9月   8 10:34 uwsgi_params.default
-rw-r--r--. 1 root root 3610 9月   8 10:34 win-utf
[root@localhost nginx]# pwd
/usr/local/nginx

啟動Nginx服務:

由於CentOS-7防火牆不開發埠,所以在本地測試中,可以選擇關閉防火牆或者允許開發80埠

CentOS防火牆

# systemctl status firewalld     ==> 防火牆狀態
# systemctl start firewalld      ==> 開啟防火牆
# systemctl stop firewalld       ==> 關閉防火牆
# systemctl restart firewalld    ==> 重啟防火牆
# firewall-cmd --reload          ==> 防火牆過載
# firewall-cmd --permanent --zone=public --add-port=80/tcp
    permanent: 永久有效
    zone:作用域
    --add-port=80/tcp:新增-埠=埠/通訊協議

開放埠或關閉防火牆後就可以啟動nginx服務

服務啟動

[root@localhost nginx]# netstat -ano | grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      off (0.00/0/0)
unix  3      [ ]         STREAM     CONNECTED     80900    
unix  3      [ ]         STREAM     CONNECTED     80899    
[root@localhost nginx]# /usr/local/nginx/sbin/nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

通過netstat檢視埠網路狀態,是否有服務佔用80埠;通過呼叫nginx的啟動目錄實現nginx服務啟動

如圖:啟動成功

Nginx服務維護

為了避免每次開機手動啟動,可以使用命令指令碼,註冊服務,開機自啟動等

建立nginx啟動命令指令碼

`vi /etc/init.d/nginx`

插入以下內容, 注意修改PATH和NAME欄位, 匹配自己的安裝路徑 (這段是從網上copy的)

`#! /bin/bash``# chkconfig: - 85 15``PATH=/usr/local/nginx``DESC=``"nginx daemon"``NAME=nginx``DAEMON=$PATH/sbin/$NAME``CONFIGFILE=$PATH/$NAME.conf``PIDFILE=$PATH/logs/$NAME.pid``SCRIPTNAME=/etc/init.d/$NAME``set` `-e``[ -x ``"$DAEMON"` `] || exit 0``do_start() {``$DAEMON -c $CONFIGFILE || echo -n ``"nginx already running"``}``do_stop() {``$DAEMON -s stop || echo -n ``"nginx not running"``}``do_reload() {``$DAEMON -s reload || echo -n ``"nginx can't reload"``}``case` `"$1"` `in``start)``echo -n ``"Starting $DESC: $NAME"``do_start``echo ``"."``;;``stop)``echo -n ``"Stopping $DESC: $NAME"``do_stop``echo ``"."``;;``reload|graceful)``echo -n ``"Reloading $DESC configuration..."``do_reload``echo ``"."``;;``restart)``echo -n ``"Restarting $DESC: $NAME"``do_stop``do_start``echo ``"."``;;``*)``echo ``"Usage: $SCRIPTNAME {start|stop|reload|restart}"` `>&2``exit 3``;;``esac``exit 0`

設定執行許可權

`chmod a+x /etc/init.d/nginx`

註冊成服務

`chkconfig --add nginx`

設定開機啟動

`chkconfig nginx ``on`

重啟, 檢視nginx服務是否自動啟動

`shutdown -h 0 -r``ss -apn|grep nginx`

對nginx服務執行停止/啟動/重新讀取配置檔案操作

`#啟動nginx服務``systemctl start nginx.service``#停止nginx服務``systemctl stop nginx.service``#重啟nginx服務``systemctl restart nginx.service``#重新讀取nginx配置(這個最常用, 不用停止nginx服務就能使修改的配置生效)``systemctl reload nginx.service`

MySQL安裝:

Linux yum-rpm

[root@localhost src]# rpm -qa |grep mysql

[root@localhost src]# wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm

[root@localhost src]# rpm -ivh mysql-community-release-el7-5.noarch.rpm

[root@localhost src]# yum dpdate

[root@localhost src]# yum install mysql-server 


[root@localhost src]# chown mysql:mysql -R /var/lib/mysql   設定許可權

[root@localhost src]# mysqld --initialize 初始化mysql

[root@localhost src]# systemctl start mysqld  啟動mysql

PHP環境:

編譯安裝php-fpm

PHP-FPM是一個PHP FastCGI管理器,是隻用於PHP的

  • 安裝依賴包
# yum -y install libmcrypt-devel mhash-devel libxslt-devel \
libjpeg libjpeg-devel libpng libpng-dvevl freetype freetype-devel libxml2 libxml2-devel \
zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel \
ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel \
krb5 krb5-devel libidn libidn-devel openssl openssl-devel


# yum -y install libzip 
# wget http://103.40.19.56/lnmp/libzip-1.3.2.tar.gz 
# tar -zxvf libzip-1.3.2.tar.gz cd libzip-1.3.2 
# ./configure 
# make && make install

# wget ftp://mcrypt.hellug.gr/pub/crypto/mcrypt/attic/libmcrypt/libmcrypt-2.5.7.tar.gz
# tar -zxvf libmcrypt-2.5.7.tar.gz
# cd libmcrypt-2.5.7
# ./configure  –prefix=/usr/local
# make && make install
  • 原始碼安裝PHP:
# cd /usr/local/src
# wget http://php.net/get/php-5.6.27.tar.gz/from/a/mirror
# tar -zxvf php-5.6.27.tar.gz
# ./configure --prefix=/usr/local/php  --enable-fpm --with-mcrypt \
--enable-mbstring --enable-pdo --with-curl --disable-debug  --disable-rpath \
--enable-inline-optimization --with-bz2  --with-zlib --enable-sockets \
--enable-sysvsem --enable-sysvshm --enable-pcntl --enable-mbregex \
--with-mhash --enable-zip --with-pcre-regex --with-pdo-mysql --with-mysqli \
--with-gd --with-jpeg-dir --with-freetype-dir --enable-calendar\
# make && make install

我在執行configure時,發生報錯:Please reinstall the libzip distribution 於是我刪除了舊版的libzip“yum remove libzip”,之後下載libzip原始碼包進行本地執行configure+make&&make install

執行libzip的安裝:

# wget https://libzip.org/download/libzip-1.5.2.tar.gz
# tar -zxf libzip-1.2.0.tar.gz

# cd libzip-1.2.0

# ./configure

# make && make install

PHP安裝新問題:安裝執行configure時報錯

configure: error: off_t undefined; check your library configuration

解決方法:

vim /etc/ld.so.conf 
#新增如下幾行
/usr/local/lib64
/usr/local/lib
/usr/lib
/usr/lib64 
#儲存退出
:wq
ldconfig -v # 執行命令,使之生效

報錯:configure: WARNING: unrecognized options: --with-mcrypt

解決方法:PHP 7.2+不支援 --with-mcrypt ; --enable-gd-native-ttf

# ./configure --prefix=/usr/local/php  --enable-fpm \
--enable-mbstring --enable-pdo --with-curl --disable-debug  --disable-rpath \
--enable-inline-optimization --with-bz2  --with-zlib --enable-sockets \
--enable-sysvsem --enable-sysvshm --enable-pcntl --enable-mbregex \
--with-mhash --enable-zip --with-pcre-regex --with-pdo-mysql --with-mysqli \
--with-gd --with-jpeg-dir --with-freetype-dir --enable-calendar\

其它錯誤可以參考百度/Google解決(常見php安裝的方案)!

至此!PHP-fpm安裝的基本流程結束了,下一步就需要配置檔案

使用者配置檔案

  • 為php提供配置檔案:php.ini
# cp php.ini-production /usr/local/php/lib/php.ini
  • 為php-fpm提供配置檔案
# cd /usr/local/php
# cp etc/php.fpm.conf.default etc/php-fpm.conf
# vi etc/php-fpm.conf

vi開啟php-fpm.conf檔案:

將檔案的尾部的索引;修改成實際的目錄

include=/usr/local/php/etc/php-fpm.d/*.conf

新增使用者和組:

useradd mirror
groupadd -g mirror mirror

預設情況下,etc/php-fpm.d/目錄下有一個“www .conf.defalut”使用者配置檔案

# cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
# vi /usr/local/php/etc/php-fpm.d/www.conf

修改“www.conf"檔案中的user和group的value;新增使用者和組

user = mirror
group = mirror
  • 啟動php-fpm服務
# /usr/local/php/sbin/php-fpm
# ps aux | grep php-fpm [驗證服務啟動]
# netstat -tln | grep 9000 [驗證網路埠是否使用]
[root@localhost /]# ps aux | grep php-fpm
root      41831  0.0  0.3 221264  6220 ?        Ss   08:54   0:00 php-fpm: master process (/usr/local/php/etc/php-fpm.conf)
mirror    41832  0.0  0.2 221264  5748 ?        S    08:54   0:00 php-fpm: pool www
mirror    41833  0.0  0.2 221264  5748 ?        S    08:54   0:00 php-fpm: pool www
root      41835  0.0  0.0 110292   916 pts/0    R+   08:54   0:00 grep --color=auto php-fpm
[root@localhost /]# netstat -tln | grep 9000
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN   

至此!php-fpm服務啟動成功!

Nginx+PHP環境配置

  • 開啟nginx.conf(nginx配置檔案)
[root@localhost nginx]# vi ./nginx.conf


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

修改server配置塊中的location和php後端請求配置塊

  server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm index.php
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

在location配置塊中新增index.php首頁

php請求和後端php-fpm模組進行通訊,需要配置location ~ .php$配置塊

​ root:配置php程式檔案的根目錄

*** 修改配置檔案的第一行:”user“屬性為我們之前配置的使用者**,表示nginx的許可權

至此!我們的Nginx和php的環境完成簡單的配置!

大功告成

啟動步驟:

  • 啟動Nginx服務

    # /usr/local/nginx/sbin/nginx
  • 啟動php-fpm服務

    # /usr/local/php/sbin/php-fpm
  • 啟動mysql服務

    # systemctl start mysqld

phpinfo():

在Nginx的目錄html中新增一個php檔案:”index.php“

<?php
    phpinfo();
?>

測試資料庫連線:

編寫一個連線資料庫行為的php檔案:”mysql.php“

php和mysql之間的連線操作依靠的是”mysqli“

<?php
    $conn = mysqli_connect("127.0.0.1","root","926498");
    if(! $conn ) {
        echo "連線失敗".mysqli_connect_error();
    } else {
        echo "連線成功";
    }
?>

至此!PHP+Nginx+MySQL環境完成了基本的搭