1. 程式人生 > >Nginx安裝、默認虛擬主機、用戶認證、nginx中PHP解析

Nginx安裝、默認虛擬主機、用戶認證、nginx中PHP解析

Nginx安裝、默認虛擬主機、用戶認證

12.6 Nginx安裝

準備工作

安裝包

[root@centos-01 ~]# cd /usr/local/src/

下載安裝包:
[root@centos-01 src]# wget http://nginx.org/download/nginx-1.12.1.tar.gz

解壓:
[root@centos-01 src]# tar zxvf nginx-1.12.1.tar.gz

安裝

環境配置

[root@centos-01 src]# cd nginx-1.12.1/

[root@centos-01 nginx-1.12.1]# ./configure --prefix=/usr/local/nginx
#如果需要支持某模塊,可以在此添加,如HTTPS、SSL等

編譯&安裝

[root@centos-01 nginx-1.12.1]# make && make install
[root@centos-01 nginx-1.12.1]# echo $?
0

[root@centos-01 nginx-1.12.1]# cd /usr/local/nginx/
[root@centos-01 nginx]# ls
conf html logs sbin

配置

添加&啟動服務

創建啟動腳本:
[root@centos-01 nginx]# vim /etc/init.d/nginx
#!/bin/bash

chkconfig: - 30 21

description: http service.

Source Function Library

. /etc/init.d/functions

Nginx Settings

NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usr/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"
start()
{
echo -n $"Starting $prog: "
mkdir -p /dev/shm/nginx_temp

daemon $NGINX_SBIN -c $NGINX_CONF
RETVAL=$?
echo
return $RETVAL
}
stop()
{
echo -n $"Stopping $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -TERM
rm -rf /dev/shm/nginx_temp
RETVAL=$?
echo
return $RETVAL
}
reload()
{
echo -n $"Reloading $prog: "
killproc -p $NGINX_PID $NGINX_SBIN -HUP
RETVAL=$?
echo
return $RETVAL
}
restart()
{
stop
start
}
configtest()
{
$NGINX_SBIN -c $NGINX_CONF -t
return 0
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
restart
;;
configtest)
configtest
;;
*)
echo $"Usage: $0 {start|stop|reload|restart|configtest}"
RETVAL=1
esac
exit $RETVAL

檢查腳本語法:
[root@centos-01 nginx]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

更改權限:
[root@centos-01 nginx]# chmod 755 /etc/init.d/nginx

添加到系統服務:
[root@centos-01 nginx]# chkconfig --add nginx
[root@centos-01 nginx]# chkconfig nginx on

更改配置文件

[root@centos-01 nginx]# cd /usr/local/nginx/conf/

註釋掉Nginx自帶腳本,創建自己的腳本:
[root@centos-01 conf]# mv nginx.conf nginx.conf.bak

[root@centos-01 conf]# vim nginx.conf

user nobody nobody;
#定義啟動Nginx的用戶
worker_processes 2;
#定義子進程數目
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
#指定Nginx最多可打開的文件數目
events
{
use epoll;
worker_connections 6000;
#進程最大連接數
}

http
{
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 3526;
server_names_hash_max_size 4096;
log_format combined_realip ‘$remote_addr $http_x_forwarded_for [$time_local]‘
‘ $host "$request_uri" $status‘
‘ "$http_referer" "$http_user_agent"‘;
sendfile on;
tcp_nopush on;
keepalive_timeout 30;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 8 4k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
client_max_body_size 10m;
client_body_buffer_size 256k;
client_body_temp_path /usr/local/nginx/client_body_temp;
proxy_temp_path /usr/local/nginx/proxy_temp;
fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
fastcgi_intercept_errors on;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 5;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/htm
application/xml;
server
#虛擬主機
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ .php$
#配置PHP解析
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
}
}
}

檢測語法:
[root@centos-01 conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

啟動Nginx服務:
[root@centos-01 conf]# /etc/init.d/nginx start
Starting nginx (via systemctl): [ 確定 ]

至此,Nginx基礎配置完成!

檢測

[root@centos-01 conf]# curl localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
使用瀏覽器檢測:

先將虛擬主機IP添加到本地hosts,然後訪問:
mark

檢測PHP解析

[root@centos-01 conf]# vim /usr/local/nginx/html/1.php
<?php
echo "welcom to adai-nginx text.";
?>

[root@centos-01 conf]# curl localhost/1.php
welcom to adai-nginx text.
瀏覽器檢測:

mark

常見的502問題解決

對於LNMP來說,最常見的就是502問題,LNMP環境搭建完成後,一訪問網站直接提示“502 Bad Gateway”。主要原因大致分為兩種:

(1)配置錯誤

在Nginx配置中有這麽一段:

location ~ .php$
#配置PHP解析
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
}
如果把fastcgi_pass(這是用來通信的)後面指定的路徑配置錯了,那麽就會出現502錯誤,因為Nginx找不到php-fpm了,fastcgi _pass後面可以跟socket也可以跟IP:port,默認監聽地址為:127.0.0.1:9000。
註意: 這裏用兩種形式都可以,但是兩個配置文件(Nginx和php-fpm)中的形式一定要統一,不然絕對502;如果用套接字形式的話,socket文件的路徑一定要對,不然也還是502。

(2)資源耗盡

LNMP架構處理PHP時,是Nginx直接調取後端的php-fpm服務,如果Nginx的請求量偏高,而我們又沒給php-fpm配置足夠的子進程數,那麽總有php-fpm資源耗盡的時候,一旦耗盡Nginx找不到php-fpm,此時也會導致502錯誤出現。解決辦法就是調整php-fpm.conf中的pm.max_children數值,使其增加。但也不能無限制增加,因為服務器的資源有限。4G內存機器如果只跑php-fpm和Nginx,不跑MySQL服務,pm.max _children可以設置為150,盡量不要超過該數值,8G內存設置為300,以此類推。

(3)listen.mode

在php-fpm配置文件中有參數listen.mode,該參數時指定php-fpm所監聽的socket文件listen = /tmp/php-fcgi.sock的權限,如果在此不指定權限,默認權限為440(只允許root用戶及root組讀取),之後在Nginx中監聽該文件時就會提示502錯誤,解決辦法就是給予socket文件讀寫權限666。

如果遇到其它的較為少見的錯誤,我們可以修改nginx的錯誤日誌(/usr/local/nginx/logs/nginx_error.log)的級別,在配置文件/usr/local/nginx/conf/nginx.conf中將crit改為debug,使其記錄最多的日誌內容,這樣方便我們排查錯誤,但是配置更改完成後要記得將級別改回crit,避免日誌文件占用太多磁盤空間。

12.7 Nginx默認虛擬主機

編輯Nginx配置文件,刪除原有server內容,添加如下內容:

創建虛擬主機

添加虛擬主機目錄

[root@centos-01 ~]# cd /usr/local/nginx/conf
[root@centos-01 conf]# vim /usr/local/nginx/conf/nginx.conf
……
include vhost/*.conf;
#創建一個虛擬主機配置文件子目錄(相當於增加子虛擬主機)

創建配置文件中的目錄文件:
[root@centos-01 conf]# mkdir vhost
註: “nginx.conf”文件中支持“include”語法。

增加一臺虛擬主機:

[root@centos-01 conf]# cd vhost

[root@centos-01 vhost]# vim aaa.com.conf

server
{
listen 80 default_server;
#有‘default_server‘標記的就是默認虛擬主機
server_name aaa.com;
index index.html index.htm index.php;
root /data/wwwroot/default;
}

創建配置文件中指定的root目錄:
[root@centos-01 vhost]# mkdir -p /data/wwwroot/default
為虛擬主機添加內容

進入目錄,添加索引頁:
[root@centos-01 vhost]# cd /data/wwwroot/default

[root@centos-01 default]# vim index.html

This is the default directory.

[root@centos-01 default]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

重啟或重新加載(二選一):
[root@centos-01 default]# /usr/local/nginx/sbin/nginx -s reload
[root@centos-01 default]# /usr/local/nginx/sbin/nginx restart
檢測

[root@centos-01 default]# curl localhost
This is the default directory.
mark

即:添加一臺虛擬主機,所謂默認虛擬主機就是/usr/local/nginx/conf/vhost目錄下虛擬主機配置文件中有“default_server”標記的虛擬主機。

12.8 Nginx用戶認證

創建一臺虛擬主機:

在vhost目錄下操作:
[root@centos-01 vhost]# vim test.com.conf

server
{
listen 80;
server_name test.com;
index index.html index.htm index.php;
root /data/wwwroot/test.com;

location /
#指定設置用戶認證的目錄
{
auth_basic "Auth";
#指定用戶名
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
#指定用戶的密碼文件
}
}
說明: 上述“location”中的內容即為設定用戶認證。在此是為整個站點設定的用戶認證,如果只是為某個目錄設置用戶認證,在location所在行進行編輯就好,如:location /admin 目錄。也可以對某種請求(即對一個普通文件)設定用戶認證,如location ~ admin.php()使用 ~ 進行匹配)。

創建密碼文件

在此需要使用Apache的/usr/local/apache/bin/htpasswd命令,如果機器中已經有Apache,可以直接使用,如果沒有,需要使用yum安裝httpd命令:

[root@centos-01 vhost]# yum install -y httpd
創建密碼文件:

[root@centos-01 vhost]# htpasswd -c /usr/local/nginx/conf/htpasswd adai
New password:
Re-type new password:
Adding password for user adai
即,創建密碼文件htpasswd,指定用戶為adai。‘-c’=create,創建該密碼文件,如果是第二次添加用戶,不用加該選項,所添加的用戶名和密碼會保存到該文件下。

重載:

[root@centos-01 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@centos-01 vhost]# /usr/local/nginx/sbin/nginx -s reload
說明: 使用reload而不使用restart的好處是能避免因配置文件中存在錯誤而無法正常啟動!reload不會破壞原有運行環境。

添加指定目錄

添加虛擬主機配置文件指定的根目錄:
[root@centos-01 vhost]# mkdir /data/wwwroot/test.com

添加索引頁:
[root@centos-01 vhost]# echo "This is test.com" >/data/wwwroot/test.com/index.html
檢測

[root@centos-01 vhost]# curl -x127.0.0.1:80 test.com -uadai:123456
This is test.com
註: 如果不指定用戶名和密碼,會報錯401(需要用戶認證);如果為創建虛擬主機根目錄會報錯404(找不到指定目錄);如果指定目錄中沒有添加索引頁(.html或.php文件)會報錯404(文件存在錯誤)。

mark

配置虛擬主機PHP解析:

編輯配置文件,添加如下location內容:

[root@centos-01 vhost]# vim /usr/local/nginx/conf/vhost/test.com.conf

location ~ \.php$
    #配置PHP解析
    {
        include fastcgi_params;
        fastcgi_pass unix:/tmp/php-fcgi.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name;
    }

}
註意: “fastcgi_param SCRIPT_FILENAME”該行路徑要和站點根目錄路徑一致,如圖:

mark

檢測:

[root@centos-01 vhost]# curl -x127.0.0.1:80 test.com/index.php
This is a test of .php
註: 此處為了方便檢測,已將用戶認證關閉。

12.9 Nginx域名重定向

編輯虛擬主機配置文件:

[root@centos-01 vhost]# vim test.com.conf

server
{
listen 80;
server_name test.com test2.com test3.com;
#為一個IP配置多個域名,此時權重會改變,所以需要使用戶訪問其他域名時全部跳轉到第一個域名
index index.html index.htm index.php;
root /data/wwwroot/test.com;
if ($host != ‘test.com‘ ) {
rewrite ^/(.*)$ http://test.com/$1 permanent;
}
#使用rewrite模塊
}

[root@centos-01 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@centos-01 vhost]# /usr/local/nginx/sbin/nginx -s reload
說明: 使用rewrite模塊進行域名重定向實現域名跳轉功能。

檢測

[root@centos-01 vhost]# curl -x127.0.0.1:80 test2.com -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Thu, 10 Aug 2017 10:41:30 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/
即,301:永久域名跳轉,跳轉後的地址為:Location: http://test.com/。

擴展:Nginx配置文件詳解

#定義Nginx運行的用戶和用戶組
user www www;

#nginx進程數,建議設置為等於CPU總核心數。
worker_processes 8;

#全局錯誤日誌定義類型,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;

#進程文件
pid /var/run/nginx.pid;

#一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(系統的值ulimit -n)與nginx進程數相除,但是nginx分配請求並不均勻,所以建議與ulimit -n的值保持一致。
worker_rlimit_nofile 65535;

#工作模式與連接數上限
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;
#單個進程最大連接數(最大連接數=連接數*進程數)
worker_connections 65535;
}

#設定http服務器
http
{
include mime.types; #文件擴展名與文件類型映射表
default_type application/octet-stream; #默認文件類型
#charset utf-8; #默認編碼
server_names_hash_bucket_size 128; #服務器名字的hash表大小
client_header_buffer_size 32k; #上傳文件大小限制
large_client_header_buffers 4 64k; #設定請求緩
client_max_body_size 8m; #設定請求緩
sendfile on; #開啟高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。註意:如果圖片顯示不正常把這個改成off。
autoindex on; #開啟目錄列表訪問,合適下載服務器,默認關閉。
tcp_nopush on; #防止網絡阻塞
tcp_nodelay on; #防止網絡阻塞
keepalive_timeout 120; #長連接超時時間,單位是秒

#FastCGI相關參數是為了改善網站的性能:減少資源占用,提高訪問速度。下面參數看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

#gzip模塊設置
gzip on; #開啟gzip壓縮輸出
gzip_min_length 1k; #最小壓縮文件大小
gzip_buffers 4 16k; #壓縮緩沖區
gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
gzip_comp_level 2; #壓縮等級
gzip_types text/plain application/x-javascript text/css application/xml;
#壓縮類型,默認就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連接數的時候需要使用

upstream blog.ha97.com {
#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的幾率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}

#虛擬主機的配置
server
{
#監聽端口
listen 80;
#域名可以有多個,用空格隔開
server_name www.ha97.com ha97.com;
index index.html index.htm index.php;
root /data/www/ha97;
location ~ ..(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
#圖片緩存時間設置
location ~ .
.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 10d;
}
#JS和CSS緩存時間設置
location ~ .*.(js|css)?$
{
expires 1h;
}
#日誌格式設定
log_format access ‘$remote_addr - $remote_user [$time_local] "$request" ‘
‘$status $body_bytes_sent "$http_referer" ‘
‘"$http_user_agent" $http_x_forwarded_for‘;
#定義本虛擬主機的訪問日誌
access_log /var/log/nginx/ha97access.log access;

#對 "/" 啟用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#後端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;
client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
client_body_buffer_size 128k; #緩沖區代理緩沖用戶端請求的最大字節數,
proxy_connect_timeout 90; #nginx跟後端服務器連接超時時間(代理連接超時)
proxy_send_timeout 90; #後端服務器數據回傳時間(代理發送超時)
proxy_read_timeout 90; #連接成功後,後端服務器響應時間(代理接收超時)
proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
proxy_buffers 4 32k; #proxy_buffers緩沖區,網頁平均在32k以下的設置
proxy_busy_buffers_size 64k; #高負荷下緩沖大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;
#設定緩存文件夾大小,大於這個值,將從upstream服務器傳
}

#設定查看Nginx狀態的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
#htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
}

#本地動靜分離反向代理配置
#所有jsp的頁面均交由tomcat或resin處理
location ~ .(jsp|jspx|do)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
#所有靜態文件由nginx直接讀取不經過tomcat或resin
location ~ ..(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{ expires 15d; }
location ~ .
.(js|css)?$
{ expires 1h; }
}
}

Nginx安裝、默認虛擬主機、用戶認證、nginx中PHP解析