nginx動靜分離介紹
nginx的靜態處理能力很強,但是動態處理能力不足,因此,在企業中常用動靜分離技術
針對php的動靜分離
-
靜態頁面交給nginx處理
-
動態頁面交給php-fpm模塊或apache處理
在nginx的配置中,是通過location配置段配合正則匹配實現靜態與動態頁面的不同處理方式
反向代理原理
nginx不僅能作為web服務器,還具有反向代理、負載均衡和緩存的功能
nginx通過proxy模塊實現將客戶端的請求代理至上游服務器,此時nginx與上游服務器的連接是通過http協議進行的
nginx在實現反向代理功能時的最重要指令為proxy_ pass,它能夠并能夠根據uri、客戶端參數或其它的處理邏輯將用戶請求調度至上游服務器
配置nginx實現動靜分離
本案例根據企業需要,將配置nginx實現動靜分離,對php頁面的請求轉發給lamp處理,而靜態頁面交給nginx處理,以實現動靜分離
架構如圖所示
配置步驟
1、架設并調試后端lamp環境
①安裝apache服務
[root@localhost ~]# yum install httpd httpd-devel -y
②在防火墻設置http服務的權限
[root@localhost?~]#?firewall-cmd?--permanent?--zone=public?--add-service=http success [root@localhost?~]#?firewall-cmd?--permanent?--zone=public?--add-service=https success??? [root@localhost?~]#?firewall-cmd?--reload? success [root@localhost?~]#?systemctl?start?httpd
③安裝mariadb
mariadb數據庫管理系統是mysql的一個分支,主要由開源社區在維護,采用gpl授權許可 mariadb的目的是完全兼容mysql,包括api和命令行,使之能輕松成為mysql的代替品
[root@localhost?~]#?yum?install?mariadb?mariadb-server?mariadb-libs?mariadb-devel?-y [root@localhost?~]#?systemctl?start?mariadb.service
④mysql安全配置向導
[root@localhost?~]#?mysql_secure_installation
⑤安裝php及支持的軟件
[root@localhost?~]#?yum?install?php?-y [root@localhost?~]#?yum?install?php-mysql?-y [root@localhost?~]#?yum?install?php-gd?php-ldap?php-odbc?php-pear?php-xml?php-xmlrpc?php-mbstring?php-snmp?php-soap?curl?curl-devel?php-bcmath?-y
⑥更改網頁主頁面
[root@localhost?~]#?cd?/var/www/html [root@localhost?html]#?vim?index.php <?php echo "this is apache test web"; ?> [root@localhost?html]#?systemctl?restart?httpd
⑦訪問測試,輸入網址
2、編譯安裝nginx
①安裝支持軟件
[root@localhost?~]#?yum?install?gcc?gcc-c++?pcre-devel?zlib-devel?-y
②創建運行用戶和組
[root@localhost?~]#?useradd?-m?-s?/sbin/nologin?nginx
③編譯安裝
[root@localhost?lnmp-c7]#?tar?zxvf?nginx-1.12.2.tar.gz?-c?/opt [root@localhost?lnmp-c7]#?cd?/opt/nginx-1.12.2/ [root@localhost?nginx-1.12.2]#?./configure? >?--prefix=/usr/local/nginx? >?--user=nginx? >?--group=nginx? >?--with-http_stub_status_module [root@localhost?nginx-1.12.2]#?make?&&?make?install [root@localhost?nginx-1.12.2]#?ln?-s?/usr/local/nginx/sbin/nginx?/usr/local/sbin
④服務管理控制
[root@localhost?~]#?vim?/etc/init.d/nginx #!/bin/bash #?chkconfig:?-?99?20 #?description:?ngins?service?control?script prog="/usr/local/nginx/sbin/nginx" pidf="/usr/local/nginx/logs/nginx.pid" case?"$1"?in start) ??$prog ??;; stop) ??kill?-s?quit?$(cat?$pidf) ??;; restart) ???$0?stop ???$0?start ???;; reload) ???kill?-s?hup?$(cat?$pidf) ???;; *) ???echo?"usage:?$0?{start|stop|restart|reload}" ???exit?1 esac exit?0 [root@localhost?~]#?chmod?+x?/etc/init.d/nginx [root@localhost?~]#?chkconfig?--add?nginx [root@localhost?~]#?service?nginx?start
⑤啟動服務
[root@nginx?~]#?systemctl?stop?firewalld.service [root@nginx?~]#?setenforce?0 [root@nginx?~]#?service?nginx?start
⑥配置nginx處理動態頁面請求
[root@nginx?~]#?vim?/usr/local/nginx/conf/nginx.conf ????location?~?.php$?{ ??????proxy_pass??http://192.168.150.214; ????} [root@nginx?~]#?service?nginx?restart
⑦訪問測試