1. 程式人生 > >Nginx服務配置綜合實例

Nginx服務配置綜合實例

https nginx

################################

1.安裝nginx,yum安裝,編譯安裝


Nginx是一個免費,開源,高性能的HTTP服務器,同時也可以作為反向代理服務器,支持IMAP/POP3郵件代理服務器,支持模塊化定制功能。

Nginx支持三種運行模式,默認為worker模式:

prefork:進程模型,兩級結構,主進程master負責生成和管理子進程,每個子進程負責響應一個請求;

worker:線程模型,三級結構,主進程負責生成子進程,每個子進程負責生成多個線程,每個線程響應一個請求;

event:兩級結構,主進程負責生成子進程,每個子進程響應多個請求;


更改nginx運行模式,通過ps/pstree來查看進程狀態變化。


nginx的安裝配置:

系統版本:centos-7.3

軟件版本:nginx-1.12.1

安裝方式:yum-epel源


官方的預制包:

http://nginx.org/packages/centos/7/x86_64/RPMS/

vi /etc/yum.repos.d/epel.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/x86_64/
#baseurl=http://nginx.org/packages/centos/7/x86_64/
gpgcheck=0
enabled=1
# yum info nginx
# yum list nginx*
# yum install nginx
# rpm -ql nginx  //查看生成的相關文件

# nginx -V //查看yum-epel源安裝nginx的默認參數及模塊

nginx version: nginx/1.12.1

built by gcc 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC)

built with OpenSSL 1.0.1e-fips 11 Feb 2013

TLS SNI support enabled

configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp ....


編譯安裝:

# yum groupinstall "Development Tools"

# yum install pcre-devel openssl-devel zlib-devel

# useradd -r nginx

# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_dav_module --with-http_stub_status_module --with-threads --with-file-aio

# make && make install


配置文件:

主配置文件:/etc/nginx/nginx.conf

獨立配置文件 conf.d/*.conf

fastcgi,uwsgi,scgi等協議相關的配置文件

mime.types:支持的mime類型

主程序文件:/usr/sbin/nginx

模塊文件:/usr/lib64/nginx/modules

服務文件:/usr/lib/systemd/system/nginx.service


查看命令幫助:nginx -h

測試配置:nginx -t

停止或重載:nginx -s stop|reload|reopen

指定配置文件:nginx -c /etc/nginx/nginx.conf

顯示編譯時的參數選項:nginx -V


################################

2.搭建簡單web站點,定義多個虛擬主機,實現負載均衡

nginx1:192.168.10.71

nginx2:192.168.10.72

nginx_proxy:192.168.10.73


================

定義一個虛擬主機:

mkdir -pv /app/vhost1 //確保網站目錄和文件的other權限有r讀權限,否則nginx用戶則無法訪問,會導致4xx錯誤

echo "Nginx vhost1 1111." > /app/vhost1/index.html
vi /etc/nginx/conf.d/vhost1.conf
server {
    server_name 192.168.10.71;
    listen 8080;
    root "/app/vhost1";
}

重啟服務

systemctl start nginx

nginx -t

nginx -s reload

ss -tnlp


訪問測試:

curl 192.168.10.71


================

定義多個虛擬主機-通過不同的端口:

mkdir -pv /app/vhost2 //確保網站目錄和文件的other權限有r讀權限,否則nginx用戶則無法訪問,會導致4xx錯誤

echo "Nginx vhost2 2222." > /app/vhost2/index.html
vi /etc/nginx/conf.d/vhost1.conf  //增加如下server配置
server {
    server_name 192.168.10.71;
    listen 8081;
    root "/app/vhost2";
}

nginx -t

nginx -s reload

ss -tnl


訪問測試:

curl 192.168.10.71:8080

curl 192.168.10.71:8081


或者通過域名來定義虛擬主機:

vi /etc/nginx/conf.d/vhost2.conf
server {
    server_name www.a.com;
    listen 80;
    root "/app/vhost1";
}
server {
    server_name www.b.com;
    listen 80;
    root "/app/vhost2";
}

vi /etc/hosts

192.168.10.71 www.a.com www.b.com


訪問測試:

nginx -s reload

curl www.a.com

curl www.b.com


================

負載均衡:

這裏使用兩個虛擬主機來模擬兩臺web服務器

vi /etc/nginx/conf.d/vhost1.conf    
server {
    server_name 192.168.10.71;
    listen 8080;
    root "/app/vhost1";
}
server {
    server_name 192.168.10.71;
    listen 8081;
    root "/app/vhost2";
}
upstream websrvs {  //設置群組名稱,以下對應上面的兩個虛擬主機
    server 192.168.10.71:8080;
    server 192.168.10.71:8081;
}
server {
    listen 8080;  //設置訪問端口
    server_name www.c.com;  //設置訪問地址
    location / {
        proxy_pass http://websrvs;  //對應上面定義的群組名稱
    }
}

增加host解析

vi /etc/hosts

192.168.10.71 www.c.com


訪問測試:

nginx -t

nginx -s reload

curl www.c.com:8080 //默認顯示為輪詢

for i in {1..10};do curl www.c.com:8080;done


################################

3.配置訪問限制和用戶認證,壓縮,日誌,代理,防盜鏈,rewrite,https,nginx狀態信息查看


================

優化nginx配置:

vi /etc/nginx/nginx.conf

worker_processes auto;

worker_cpu_affinity auto;

worker_priority -3;


查看進程和優先級

ps axo pid,comm,psr,ni | grep nginx


ngx_http_access_module模塊:

實現基於ip的訪問控制功能

vi /etc/nginx/conf.d/vhost1.conf 
server {
    server_name 192.168.10.71;
    listen 8080;
    root "/app/vhost1";
    location / {
        deny 192.168.10.72;
        allow 192.168.10.73;
        deny all;
    }
}

================

ngx_http_auth_basic_module模塊:

實現基於用戶的訪問控制,使用basic機制進行用戶認證

vi /etc/nginx/conf.d/vhost1.conf  //替換location配置如下
location / {
    auth_basic "admin auth";
    auth_basic_user_file "/etc/nginx/.ngxpasswd";
}

yum install httpd-tools

htpasswd -c -m /etc/nginx/.ngxpasswd user1 //提示輸入密碼,首個用戶需要加-c參數

htpasswd -m /etc/nginx/.ngxpasswd user2

more /etc/nginx/.ngxpasswd


測試訪問:

yum install elinks

elinks 192.168.10.71:8080 //提示輸入用戶名和密碼才能訪問


================

ngx_http_stub_status_module模塊:

用於輸出nginx的基本狀態信息

vi /etc/nginx/conf.d/vhost1.conf 替換location配置如下

location /basic_status {

stub_status;

}


測試訪問:

curl 192.168.10.71:8080/status

Active connections: 1

server accepts handled requests

67 67 102

Reading: 0 Writing: 1 Waiting: 0


================

ngx_http_gzip_module模塊:

用於壓縮頁面文件,減少帶寬的浪費

location / {
    gzip  on;
    gzip_comp_level 6;
    gzip_min_length 64;
    gzip_proxied any;
    gzip_types text/xml text/css text/txt application/javascript;
}

cp /var/log/messages /app/vhost1/messages.txt

chmod 644 /app/vhost1/messages.txt


測試訪問:

通過chrome或者Firefox訪問

http://192.168.10.71:8080/messages.txt

按F12顯示開發者工具欄,強制刷新會顯示Size大小明顯變小,並顯示如下調試信息

Accept-Encoding:gzip, deflate


================

ngx_http_ssl_module模塊:

配置加密的https


配置CA證書服務器,IP-10.72:

cd /etc/pki/CA

touch index.txt

echo 01 > serial

(umask 077; openssl genrsa -out private/cakey.pem 2048)

openssl req -new -x509 –key /etc/pki/CA/private/cakey.pem -days 7300 -out /etc/pki/CA/cacert.pem

提示輸入國家,省,市,公司名稱,部門名稱,CA主機名(頒發者名稱)

C=CN, ST=HA, L=ZZ, O=c73, OU=IT, CN=ca.a.com

查看生成的證書

openssl x509 -in /etc/pki/CA/cacert.pem -noout -text


生成並發送web服務器(10.71)的證書請求文件到CA服務器(10.72):

在web服務器上生成證書請求文件,此處的key文件對應nginx中的ssl-key配置路徑

(umask 077; openssl genrsa -out /app/service.key 2048)

openssl req -new -key /app/service.key -out /app/service.csr

同樣提示輸入國家,省,市等信息。註意:國家,省,公司名稱三項必須和CA一致。主機名稱必須和網站域名相同,如www.a.com。或者使用泛域名,即*.a.com,匹配所有。

scp /app/service.csr 192.168.10.72:/etc/pki/CA/certs/


CA服務器簽署證書,並將證書頒發給web服務器,註意證書文件後綴為*.crt

openssl ca -in /etc/pki/CA/certs/service.csr –out /etc/pki/CA/certs/service.crt -days 365

scp /etc/pki/CA/certs/service.crt 192.168.10.71:/app/


配置nginx支持https訪問:

vi /etc/nginx/vhost1.conf  
server {
    listen 443 ssl;
    server_name www.a.com;
    root /app/vhost1;
    ssl on;
    ssl_certificate /app/service.crt;  //證書文件路徑
    ssl_certificate_key /app/service.key;  //key文件路徑
    ssl_session_cache shared:sslcache:20m;
}

通過瀏覽器訪問:

https://192.168.10.71


或者通過命令行訪問

curl https://192.168.10.71 //直接訪問會提示證書不可用

curl -k https://192.168.10.71 //加上-k參數就可以忽略證書訪問


================

ngx_http_rewrite_module模塊:

配置URL重定向,將/bbs跳轉到vhost2虛擬主機上

vi /etc/nginx/conf.d/vhost1.conf 
server {
    server_name 192.168.10.71;
    listen 8080;
    root "/app/vhost1";
    location / {
        rewrite ^/bbs/(.*)$ http://192.168.10.71:8081;
    }
}
server {
    server_name 192.168.10.71;
    listen 8081;
    root "/app/vhost2";
}

註意:需要創建/app/vhost1/bbs目錄

mkdir /app/vhost1/bbs


通過瀏覽器訪問自動跳轉到vhost2定義的頁面

http://192.168.10.71/bbs


通過命令行訪問:

curl -I 192.168.10.71:8080/bbs

代碼提示301,並顯示

Location: http://192.168.10.71:8080/bbs/


------------------------

配置永久跳轉http-->https

vi /etc/nginx/conf.d/default.conf //在server配置段增加如下一行內容

rewrite ^(.*)$ https://$host$1 permanent;


通過瀏覽器訪問http自動跳轉到https

http://192.168.10.71


通過命令行訪問

elinks http://192.168.10.71

curl -I 192.168.10.71 //代碼提示301跳轉,並顯示location位置為https://


================

ngx_http_referer_module模塊:

nginx防盜鏈,配置只允許通過*.a.com和*.b.com來鏈接訪問,其他均拒絕:

vi /etc/nginx/conf.d/vhost1.conf 
server {
    server_name www.a.com;
    listen 8080;
    root "/app/vhost1";
    valid_referers none block server_names *.a.com *.b.com;
    if ($invalid_referer) {
        return 403;
    }
}

通過命令行測試:

# curl -e "http://www.b.com:8080" "http://www.a.com:8080"

Nginx vhost1 1111. //訪問正常

# curl -e "http://www.c.com:8080" "http://www.a.com:8080"

顯示403 Forbidden //無法訪問,鏈接失敗


================

ngx_http_proxy_module模塊:

http代理,配置/bbs/跳轉到vhost2虛擬主機

vi /etc/nginx/conf.d/vhost1.conf
server {
    server_name 192.168.10.71;
    listen 8080;
    root "/app/vhost1";
    location /bbs/ {
        proxy_pass http://192.168.10.71:8081/;
    }
}
server {
    server_name 192.168.10.71;
    listen 8081;
    root "/app/vhost2";
}

註意以下情況proxy_pass最後均不能添加URI:

當location中定義了正則表達式;當location包含在named localtion或者if語句或者limit_except三者中時,不能添加URI。


通過命令行訪問:

curl 192.168.10.71:8080

curl 192.168.10.71:8080/bbs/ 跳轉到vhost2的虛擬主機頁面


================

ngx_http_log_module模塊

日誌

log_format compression ‘$remote_addr - $remote_user [$time_local] ‘
                      ‘"$request" $status $bytes_sent ‘
                      ‘"$http_referer" "$http_user_agent" "$gzip_ratio"‘;
access_log /spool/logs/nginx-access.log compression buffer=32k;

顯示的日誌格式如下:

more /var/log/nginx/access.log

192.168.10.71 - - [08/Sep/2017:11:28:37 +0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"


================

ngx_http_fastcgi_module模塊:

配置php-fpm服務

yum install -y php-fpm //註意fpm和php有沖突

vi /etc/php-fpm.d/www.conf

user = nginx

group = nginx


systemctl start php-fpm

ss -tnl //是否監聽9000端口

vi /app/vhost2/index.php 
<?php
    phpinfo();
?>

配置fastcgi代理,配置通過/status和/ping來獲取fpm server狀態信息;

vi /etc/nginx/conf.d/vhost1.conf 
server {
    server_name 192.168.10.71;
    listen 8080;
    root "/app/vhost2";
    index index.php;
    location ~* \.php$ {
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /app/vhost2$fastcgi_script_name;
        include        fastcgi_params;
    }
    location ~* ^/(status|ping)$ {
        fastcgi_pass    127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  $fastcgi_script_name;
        include        fastcgi_params;
    }
}

瀏覽器測試:

http://192.168.10.71:8080

顯示信息:Server API FPM/FastCGI


狀態信息:

http://192.168.10.71:8080/status?full

http://192.168.10.71:8080/status?json

http://192.168.10.71:8080/status?xml

http://192.168.10.71:8080/ping //正常顯示為pong,顯示信息可以在php-fpm配置文件中更改ping.response參數



################################

4.搭建WordPress站點,兩臺主機實現lanmp-(nginx+httpd+php+mariadb)

nginx實現php解析的2中方式:

nginx+fastcgi_module+php-fpm--單臺主機

nginx+httpd_lamp--兩臺主機(推薦)

server1: 192.168.10.71

server2: 192.168.10.72

server1配置nginx實現靜態頁面處理;server2配置lamp實現動態頁面處理;server1配置代理,實現動靜分離,即將*.php動態頁面轉發給server2,由server2處理後返回結果頁面給server1。


配置lamp服務

yum install -y httpd php-mysql mariadb-server php

systemctl start httpd

systemctl start mariadb

測試httpd服務

echo "httpd test" >/var/www/html/index.html

vi /var/www/html/index.php

<?php

phpinfo();

?>

curl 127.0.0.1

curl 127.0.0.1/index.php


配置mariadb

mysql

mysql_secure_installation

mysql -uroot -p

創建數據庫

MariaDB [(none)]> create database wpdb;

MariaDB [(none)]> grant all on wpdb.* to [email protected]‘192.168.10.%‘ identified by "redhat";


配置WordPress站點

cp wordpress-4.7.4-zh_CN.tar.gz /var/www/html/
cp phpMyAdmin-4.0.10.20-all-languages.zip /var/www/html/
cd /var/www/html/
tar -xf wordpress-4.7.4-zh_CN.tar.gz 
unzip phpMyAdmin-4.0.10.20-all-languages.zip    //註意版本選擇4.0版
ln -s wordpress wp
ln -s phpMyAdmin-4.0.10.20-all-languages pma
cp wp-config-sample.php wp-config.php
vi wp-config.php  //更改wp的配置文件
define(‘DB_NAME‘, ‘wpdb‘);
define(‘DB_USER‘, ‘wpuser‘);
define(‘DB_PASSWORD‘, ‘redhat‘);
define(‘DB_HOST‘, ‘192.168.10.71‘);
vi /etc/httpd/conf/httpd.conf  //增加首頁文件index.php
DirectoryIndex index.php index.html
yum install php-mbstring  //使用pma需要安裝此模塊
systemctl restart httpd

訪問測試:

http://192.168.10.72/wp

http://192.168.10.72/pma

賬號和密碼為本地數據庫的賬號和密碼,pma默認登錄本地數據庫


配置nginx服務,實現動靜分離

vi /etc/nginx/conf.d/default.conf  
server {
    listen      80;
    server_name  192.168.10.71;
    location / {
        root  /usr/share/nginx/html;
        index  index.php index.html;
    }
    location ~* \.php$ {
        proxy_pass  http://192.168.10.72;
        index index.php index.html;
    }
}

新建兩個測試頁

nginx-server1:

echo "nginx-web-server-10.71" > /usr/share/nginx/html/test.html

httpd-server2:

echo "httpd-php-web-server-10.72" /var/www/html/test.php


通過瀏覽器測試:

http://192.168.10.71/test.html

http://192.168.10.71/test.php

可以看到nginx實現*.php轉發給後端的lamp處理,但是首頁文件index.php測試無效果,即不能通過http://192.168.10.71/index.php直接訪問到後端的WordPress站點。


可以通過URL跳轉的方式來訪問後端站點,增加如下的代理配置

location /wp/ {
    proxy_pass http://192.168.10.72/;
    index index.php;
}

測試,首次打開網站比較慢:

http://192.168.10.71/wp/


################################

5.配置stream模塊,實現ssh代理和負載均衡

stream配置和http配置相沖突,所以需要註釋或刪除http配置段

vi /etc/nginx/nginx.conf 
user  nginx;
worker_processes  auto;
worker_cpu_affinity auto;
worker_priority -3;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
    #accept_mutex on;
}
stream {
    upstream sshsrvs {
        server 192.168.10.72:22;
        server 192.168.10.73:22;
    #    ip_hash;
        hash $remote_addr consistent;
    }
    server {
        listen 192.168.10.71:22222;
        proxy_pass sshsrvs;
        proxy_timeout 60s;
        proxy_connect_timeout 10s;
    }
}

登錄測試:

ssh 192.168.10.71 -p 22222


本文出自 “rackie” 博客,請務必保留此出處http://rackie386.blog.51cto.com/11279229/1963921

Nginx服務配置綜合實例