【第六課】Nginx經常使用配置下詳解

Nginx經常使用配置下詳解

一、Nginx虛擬主機

  所謂虛擬主機,在Web服務當中就是一個獨立的網站站點,這個站點對應獨立的域名(也有多是IP或者端口),具備獨立的程序和資源目錄,能夠獨立地對外提供服務供用戶訪問。css

​ 這個獨立的站點在配置裏是由必定格式的標籤進行標記,和apache相對比,apache的虛擬主機的標籤段一般是以 進行標註的,而Nginx則是以Server{}標籤段來標示一個虛擬主機。一個Web服務中支持多個虛擬主機站點。html

和apache同樣,虛擬主機主要有3種:前端

  • (1)基於域名的虛擬主機
  • (2)基於端口的虛擬主機
  • (3)基於IP的虛擬主機

(1)基於域名域名的虛擬主機配置mysql

(1)修改主配置文件nginx.conf,加載虛擬主機配置
[root@localhost conf]# grep -Ev "^$|#" nginx.conf
user  nginx;
worker_processes  auto;
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"';
    sendfile        on;
    tcp_nopush     on;
    keepalive_timeout  65;
    include /usr/local/nginx/conf/vhosts/*.conf;  #包含虛擬主機配置
}

(2)建立虛擬主機配置文件,並增長虛擬主機
[root@localhost conf]# mkdir vhosts && cd vhosts/
[root@localhost vhosts]# vim www.abc.org.conf
server {
        listen 80;
        server_name www.abc.org;
        root /vhosts/html/www;
        index index.html index.htm index.php;
}
[root@localhost vhosts]# cp www.abc.org.conf bbs.abc.org.conf
[root@localhost vhosts]# cp www.abc.org.conf blog.abc.org.conf
[root@localhost vhosts]# vim bbs.abc.org.conf 
server {
        listen 80;
        server_name bbs.abc.org;
        root /vhosts/html/bbs;
        index index.html index.htm index.php;
}
[root@localhost vhosts]# vim blog.abc.org.conf 
server {
        listen 80;
        server_name blog.abc.org;
        root /vhosts/html/blog;
        index index.html index.htm index.php;
}

(3)建立虛擬主機主頁
[root@localhost vhosts]# mkdir /vhosts/html/{www,bbs,blog}
[root@localhost vhosts]# echo "welcome to www.abc.org" >> /vhosts/html/www/index.html
[root@localhost vhosts]# echo "welcome to bbs.abc.org" >> /vhosts/html/bbs/index.html
[root@localhost vhosts]# echo "welcome to blog.abc.org" >> /vhosts/html/blog/index.html

(4)檢查語法,重載nginx
[root@localhost vhosts]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx1.15.1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.15.1/conf/nginx.conf test is successful
[root@localhost vhosts]# /usr/local/nginx/sbin/nginx -s reload

windows下作hosts解析nginx

192.168.56.11 www.abc.org bbs.abc.org blog.abc.org 分別訪問git

imgimgimg

(2)基於端口的虛擬主機配置web

(1)修改bbs和blog站點監聽端口
[root@localhost vhosts]# vim bbs.abc.org.conf 
listen 8081;
[root@localhost vhosts]# vim blog.abc.org.conf 
listen 8082
[root@localhost vhosts]# export PATH=/usr/local/nginx/sbin/:$PATH

(2)檢查語法,重載nginx
[root@localhost vhosts]# nginx -t
nginx: the configuration file /usr/local/nginx1.15.1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.15.1/conf/nginx.conf test is successful
[root@localhost vhosts]# nginx -s reload

(3)測試訪問頁面
[root@localhost ~]# curl www.abc.org
welcome to www.abc.org
[root@localhost ~]# curl bbs.abc.org:8081
welcome to bbs.abc.org
[root@localhost ~]# curl blog.abc.org:8082
welcome to blog.abc.org

以上端口能夠隨意更改,可是不能和已有服務衝突,原則上應該是大於1024小於65535的任意端口sql

(3)基於IP的虛擬主機配置數據庫

(1)增長虛擬網卡eth0:0和eth0:1
[root@localhost ~]# ifconfig eth0:0 192.168.56.110/24 up
[root@localhost ~]# ifconfig eth0:1 192.168.56.111/24 up
[root@localhost ~]# ifconfig eth0:0
eth0:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.110  netmask 255.255.255.0  broadcast 192.168.56.255
        ether 00:0c:29:ce:31:fd  txqueuelen 1000  (Ethernet)

[root@localhost ~]# ifconfig eth0:1
eth0:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.111  netmask 255.255.255.0  broadcast 192.168.56.255
        ether 00:0c:29:ce:31:fd  txqueuelen 1000  (Ethernet)

(2)修改虛擬主機配置server_name爲ip訪問
[root@localhost vhosts]# vim bbs.abc.org.conf 
listen 8081;
server_name 192.168.56.110;
[root@localhost vhosts]# vim blog.abc.org.conf 
listen 8082;
server_name 192.168.56.111;

(3)檢測語法,重載nginx,測試訪問
[root@localhost vhosts]# nginx -t
nginx: the configuration file /usr/local/nginx1.15.1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.15.1/conf/nginx.conf test is successful
[root@localhost vhosts]# nginx -s reload
[root@localhost ~]# curl http://192.168.56.110:8081/
welcome to bbs.abc.org
[root@localhost ~]# curl http://192.168.56.111:8082/
welcome to blog.abc.org

二、部署wordpress開源博客

(1)MySQL數據庫配置準備

[root@localhost tools]# wget https://cn.wordpress.org/wordpress-4.9.4-zh_CN.tar.gz    //下載wordpress源碼包
[root@localhost tools]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 24
Server version: 5.6.35 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database wordpress default character set = 'utf8';    //建立wordpress專用數據庫,用於存放blog數據
Query OK, 1 row affected (0.00 sec)

mysql> show databases like "wordpress";
+----------------------+
| Database (wordpress) |
+----------------------+
| wordpress            |
+----------------------+
row in set (0.02 sec)

mysql> grant all on wordpress.* to wordpress@'%' identified by '123456';    //受權數據庫管理用戶
Query OK, 0 rows affected (0.02 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> quit;
Bye

(2)Nginx和PHP配置準備

[root@localhost vhosts]# vim wordpress.conf     //編輯博客虛擬主機配置
server {
        listen 80;
        server_name blog.test.com;
        root /vhosts/html/wordpress;
        index index.html index.php index.htm;

        access_log logs/blog.test.com_access.log main;
        error_log logs/blog.test.com_error.log info;

        location ~ \.php$ {
            root           /vhosts/html/wordpress;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }


}
[root@localhost tools]# tar -zxf wordpress-4.9.4-zh_CN.tar.gz     //解壓博客源碼包
[root@localhost tools]# mv wordpress /vhosts/html/
[root@localhost wordpress]# chown -R nginx.nginx /vhosts/html/wordpress        //更改所屬權限
[root@localhost wordpress]# nginx -t
nginx: the configuration file /usr/local/nginx1.15.1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.15.1/conf/nginx.conf test is successful
[root@localhost wordpress]# nginx -s reload

windows下作hosts域名解析 192.168.56.11 blog.test.com,訪問blog.test.com,出現如下界面,進行安裝wordpress

填寫數據庫相關信息

提交後,點擊如今安裝,然後輸入博客相關信息。完成後登陸博客,可進入到博客內部,如圖:

在此界面能夠進行發佈文章,發佈完成後,從新訪問blog.test.com時,則跳到了正常的博客訪問頁面。

三、部署discuz開源論壇

[root@localhost web]# git clone https://gitee.com/ComsenzDiscuz/DiscuzX.git    #下載discuz論壇源碼包
Cloning into 'DiscuzX'...
remote: Enumerating objects: 7404, done.
remote: Counting objects: 100% (7404/7404), done.
remote: Compressing objects: 100% (4767/4767), done.
remote: Total 7404 (delta 2663), reused 7153 (delta 2588)
Receiving objects: 100% (7404/7404), 12.12 MiB | 471.00 KiB/s, done.
Resolving deltas: 100% (2663/2663), done.

[root@localhost vhost]# cp -r /data/web/DiscuzX/upload /data/web/discuz    #拷貝源碼到站點根目錄

[root@localhost vhost]# cat discuz.conf     #增長論壇虛擬主機配置
server {
    listen       80;
    server_name  192.168.56.11;
    root /data/www/discuz;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri = 404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

[root@localhost vhost]# 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@localhost vhost]# systemctl reload nginx

[root@localhost vhost]# mysql -uroot -p    #登陸數據庫,建立須要的庫和用戶名
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.1.20-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database discuz default charset utf8;
Query OK, 1 row affected (0.05 sec)

MariaDB [(none)]> grant all privileges on discuz.* to discuz@"%" identified by "123456";
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

訪問192.168.56.11,能夠進入安裝界面,如圖:






四、域名重定向

需求:訪問blog.bbb.com域名,能夠自動跳轉到blog.aaa.com域名進行訪問

[root@localhost vhost]# curl blog.aaa.com    #訪問頁面
welcome to blog index.html
[root@localhost vhost]# vim blog.conf 
server {
    listen       80;
    server_name  blog.aaa.com blog.bbb.com;
    root /data/web/blog;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    if ($host = blog.bbb.com) {    #使用if進行判斷,若是域名爲blog.bbb.com則進行跳轉
        rewrite /(.*) http://blog.aaa.com/$1 permanent;
    }

    location ~ \.php$ {
        try_files $uri = 404;
        fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

[root@localhost vhost]# 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@localhost vhost]# systemctl reload nginx

[root@localhost vhost]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.56.11 blog.aaa.com blog.bbb.com

[root@localhost vhost]# curl blog.bbb.com    #訪問blog.bbb.com會提示301跳轉信息
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.12.2</center>
</body>
</html>
[root@localhost vhost]# curl blog.bbb.com -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.2
Date: Thu, 14 Feb 2019 07:07:46 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://blog.aaa.com/

五、Nginx用戶認證

(1)添加test用戶,並使用md5加密
[root@localhost vhosts]# htpasswd -c -m /usr/local/nginx/conf/htpasswd test
New password: 123456
Re-type new password: 123456
Adding password for user test

(2)修改虛擬主機配置文件
[root@localhost vhosts]# vim www.abc.org.conf 
server {
        listen 80;
        server_name www.abc.org;
        root /vhosts/html/www;
        index index.html index.htm index.php;

        location /nginx_status {
                auth_basic "Please input your acount";  #添加認證提示
                auth_basic_user_file /usr/local/nginx/conf/htpasswd;  #指定basic的密碼文件
                stub_status on;
                access_log off;

        }
}

(3)檢測語法,重載nginx
[root@localhost vhosts]# nginx -t
nginx: the configuration file /usr/local/nginx1.15.1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.15.1/conf/nginx.conf test is successful
[root@localhost vhosts]# nginx -s reload

六、Nginx訪問日誌配置

Nginx軟件會把每一個用戶訪問網站的日誌信息都記錄到指定的日誌文件中,可讓運維人員更好地分析用戶的瀏覽行爲,該功能由ngx_http_log_module模塊負責。其訪問日誌主要有2個參數控制:
log_format:定義記錄日誌的格式
access_log:指定日誌子文件的路徑以及使用哪一種日誌格式記錄。
Nginx的默認日誌格式以下:

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

日誌中的變量說明:
$remote_addr:記錄訪問網站的客戶端地址
$http_x_forwarded_for:當前端有代理服務器時,設置Web節點記錄客戶端地址的配置,此參數生效的前提是代理服務器上也進行了相關的x_forwarded_for設置
$remote_user:遠程客戶端用戶名稱
$time_local:記錄訪問時間和時區
$request:用戶的http請求起始行信息
$status:http狀態碼,記錄請求返回的狀態,例如:200、503
$body_bytes_sents:服務器發送給客戶端的響應主體字節數
$http_referer:記錄這次請求是從哪一個連接訪問過來的,能夠根據referer進行防盜鏈設置
$http_user_agent:記錄客戶端訪問信息,例如:瀏覽器、手機客戶端等

記錄日誌配置以下:

access_log logs/access.log main;

實際應用例子:

[root@localhost vhosts]# cat /usr/local/nginx/logs/www.abc.org_access.log   #每一個對應相應的顏色
192.168.56.1 - test [17/Jul/2018:07:20:44 -0400] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36" "-"
$remoote_addr - $remote_user [time_local]       $request  $status  $body_bytes_sent  $http_referer  $$http_user_agent                                         $http_x_forwarded_for

在記錄日誌參數中加上buuffer和flush選項,能夠在高併發的場景下提高網站的訪問性能。buffer=size爲存放訪問日誌的緩衝區大小,flush=time爲將緩衝區的日誌刷到磁盤的時間,gzip[=level]表示壓縮級別。配置舉例以下:

access_log logs/www.abc.org_access.log main gzip buffer=32k flush=5s;

七、Nginx日誌不記錄靜態文件和靜態文件過時緩存

因爲日誌記錄會逐漸龐大,能夠對某些資源的訪問日誌取消記錄,配置以下:

location ~.*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$
{
expires 30d;       //配置圖片緩存時間
access_log off;    //表示不記錄gif|jpg等類型文件
}

location ~ .*\.(js|css)$
{
     expires 12h;     //配置圖片緩存時間
     access_log off;
}

過時時間指的是圖片會在瀏覽器存儲指定時間,超過這個時間就會從新刷新,配置緩存的目的是爲了讓網站的訪問速度更加快,節省帶寬。

八、日誌切割

默認的狀況下Nginx會把全部的訪問日誌都輸出到一個access.log的日誌當中,時間久了,就會致使日誌臃腫,不利於分析和處理,因此有必要地對日誌進行按天或按小時進行切割保存。切割的方式Nginx並無像apache同樣自帶日誌切割工具(rotatelogs),因此只能使用腳本的方式對日誌進行切割。腳本以下:

[root@localhost ~]# vim cut_nginx_log.sh
#!/bin/bash
Dateformat=$(date +%Y%m%d)
Basedir="/usr/local/nginx"
Nginxlogdir="$Basedir/logs"
Logname="access_www"
[ -d $Nginxlogdir ] && cd $Nginxlogdir || exit 1
[ -f ${Logname}.log || exit 1
/bin/mv ${Logname}.log ${Dateformat}_${Logname}.log
$Basedir/sbin/nginx -s reload

[root@localhost ~] crontab -e  #定時任務實現天天00點執行日誌切割腳本
00 * * * /bin/bash /root/cut_nginx_log.sh >/dev/null 2>&1

九、Nginx配置防盜鏈

若是一個網站的圖片較多,好比淘寶,每一個商品都有不少圖片來展現商品,本公司也是作電商產品,有本身的平臺,圖片也是較多的。可是若是相應的同行就會有競爭,若是被競爭對手拿到了公司網站上的圖片連接,而後放到他的網站上訪問,這樣競爭對手網站上的圖片走的訪問路徑是走本公司的,流量也就在本公司服務器上產生,這會致使成本的增長,因此須要禁止別的網站轉載本身網站上的圖片。可在虛擬主機中配置:

location ~.*\.(gif|jpg|jpeg|png|bmp|swf|flv|rar|zip|gz|bz2)$
{
               expires 30d;       //配置圖片緩存時間
               access_log off;    //表示不記錄gif|jpg等類型文件
               valid_referers none blocked servernames *.taobao.com *.baidu.com *.google.com;
               if ($invalid_referer )
               {
                        return 403;
                        rewirte ^/http://www.abc.org/nophoto.gif;
               }
}


valid_referers是可用的來源鏈,
none bolocked server_names是不進行防盜的主機域名,加起來是對於這些可用的連接不進行攔截而是加入白名單。
$invalid_referer,這裏用$做爲一個變量,變量名是不可用的來源鏈,和可用的正好相反
盜用咱們圖片的人訪問這些圖片時會跳轉到http://www.abc.org/nophoto.gif,也能夠直接顯示403,這樣更節省資源。

十、Nginx的訪問控制

爲了實現網站的安全,或者說是某些頁面的限制訪問,又或者是某個惡意ip的拒絕訪問,均可以經過ngx_http_access_module模塊容許限制對某些客戶端地址的訪問。
官方文檔示例:

location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

按順序檢查規則,直到找到第一個匹配項。在此示例中,僅容許IPv4網絡 10.1.1.0/16以及192.168.1.0/24 但不包括地址192.168.1.1,以及IPv6網絡2001:0db8::/32對網站進行訪問。若是有不少規則, 最好使用 ngx_http_geo_module模塊變量。
語法:

語法:    allow address | CIDR | unix: | all;
默認值:    —
應用區段:    http, server, location, limit_except

容許訪問的IP。若是unix:指定了特殊值(1.5.1),則容許訪問全部UNIX域套接字。

語法:    deny address | CIDR | unix: | all;
默認值:    —
應用區段:    http, server, location, limit_except

拒絕訪問的IP。若是unix:指定了特殊值(1.5.1),則拒絕全部UNIX域套接字的訪問。

實際應用舉例,對nginx_status進行限制訪問

[root@localhost vhosts]# vim www.abc.org.conf   #修改虛擬主機配置文件
server {
        listen 80;
        server_name www.abc.org abc.org;
        root /vhosts/html/www;
        index index.html index.htm index.php;
        if ( $host != www.abc.org )
        {
                rewrite ^/(.*)$ http://www.abc.org/$1 permanent;
        }

        access_log logs/www.abc.org_access.log main;
        error_log logs/www.abc.org_error.log crit;
        location /nginx_status {
                #auth_basic "Please input your acount";
                #auth_basic_user_file /usr/local/nginx/conf/htpasswd;
                allow 192.168.56.11;  #容許192.168.56.11該ip訪問
                deny all;         #拒絕其餘全部的訪問
                stub_status on;
                access_log off;

        }
}
[root@localhost vhosts]# nginx -t
nginx: the configuration file /usr/local/nginx1.15.1/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.15.1/conf/nginx.conf test is successful
[root@localhost vhosts]# nginx -s reload
[root@localhost ~]# curl http://www.abc.org/nginx_status  #本機訪問測試,能夠獲取到nginx的狀態信息
Active connections: 1 
server accepts handled requests
36 38 
Reading: 0 Writing: 1 Waiting: 0

windows下訪問:http://www.abc.org/nginx_status,會直接提示403,權限拒絕了其餘訪問

還能夠將訪問的規則定義在整個server段,表示對網站的訪問進行限制,也能夠在http段進行限制,表示對全局的站點進行限制訪問。

十一、生成SSL祕鑰加密網站

要生成ssl加密網站,就須要用到nginx的另外一個模塊:ngx_http_ssl_module,該模塊提供https支持,默認狀況下不會使用該模塊,須要在編譯時增長編譯參數:--with-http_ssl_module,且該模塊還須要openssl庫的支持

示例配置:

worker_processes auto;  #配置work進程數量

http {

    ...

    server {
        listen              443 ssl;  #監聽443端口,啓用ssl
        keepalive_timeout   70;     #啓用保持活動鏈接

        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;  #ssl寫協議配置
        ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;  #ssl加密方式
        ssl_certificate     /usr/local/nginx/conf/cert.pem;  #指定證書文件
        ssl_certificate_key /usr/local/nginx/conf/cert.key;  #指定私鑰文件
        ssl_session_cache   shared:SSL:10m;  #啓用共享會話緩存
        ssl_session_timeout 10m;  #ssl會話延時配置

        ...
    }

https配置實例:

(1)生成pem證書和私鑰
[root@localhost conf]# openssl genrsa -out cert.key 2048    //生成私鑰
Generating RSA private key, 2048 bit long modulus
...................................+++
....+++
e is 65537 (0x10001)
[root@localhost conf]# openssl req -new -x509 -key cert.key -out cert.pem    //生成證書
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:zhongshan
string is too long, it needs to be less than  2 bytes long
Country Name (2 letter code) [XX]:zhognshan
string is too long, it needs to be less than  2 bytes long
Country Name (2 letter code) [XX]:zx
State or Province Name (full name) []:zx
Locality Name (eg, city) [Default City]:zx
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:

(2)查看證書
[root@localhost conf]# ll cert.*    
-rw-r--r-- 1 root root 1675 Jul 17 09:59 cert.key
-rw-r--r-- 1 root root 1229 Jul 17 10:00 cert.pem

(3)配置虛擬主機
[root@localhost vhosts]# cat www.abc.org.conf www.abc.org.ssl.conf 
server {
    listen 80;
    server_name www.abc.org abc.org;
    root /vhosts/html/www;
    index index.html index.htm index.php;
    rewrite ^/(.*)$ https://$host/$1 permanent;    //配置http訪問時強制跳轉到https
    
    access_log logs/www.abc.org_access.log main;
    error_log logs/www.abc.org_error.log crit;    

}
server {                //ssl站點配置
    listen 443 ssl;
    server_name www.abc.org abc.org;
    root /vhosts/html/www;
    index index.html index.htm index.php;
      ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
        ssl_certificate     /usr/local/nginx/conf/cert.pem;
        ssl_certificate_key /usr/local/nginx/conf/cert.key;
        ssl_session_cache   shared:SSL:10m;
        ssl_session_timeout 10m;    
    location /nginx_status {
                #auth_basic "Please input your acount";
                #auth_basic_user_file /usr/local/nginx/conf/htpasswd;
                #allow 192.168.56.11;
                #deny all;
                #include deny.ip;
                stub_status on;
                access_log off;

        }

}

訪問:http://www.abc.org/nginx_status會自動跳轉到https://www.abc.org/nginx_status,如圖:

網站添加了https證書後,當http方式訪問網站時就會報404錯誤,因此須要作http到https的強制跳轉設置。如下總結http跳轉https的方法:
1) 下面是將全部的http請求經過rewrite重寫到https上。

[root@localhost vhosts]# vim www.abc.org.conf     //僅修改www.abc.org.conf
server {
        listen 80;
        server_name www.abc.org abc.org;
        root /vhosts/html/www;
        index index.html index.htm index.php;
        #rewrite ^/(.*)$ https://$host/$1 permanent;        //方法一:這是nginx早前寫法,一直有效
        #return 301 https//$server_name$request_uri;        //方法二:這是nginx支持的最新寫法
        #if ($host ~* "^abc.org$"){                            //方法三:用if判斷跳轉,適用於多域名,即便訪問abc.org也會跳轉
        #        rewrite ^/(.*)$ https//www.abc.org/ permanent;
        #}
        if ($host  = "www.abc.org"){                        //方法四:對$host作精確判斷跳轉
                rewrite ^/(.*)$ https://www.abc.org/ permanent;
        }
        access_log logs/www.abc.org_access.log main;
        error_log logs/www.abc.org_error.log crit;

}

2)採用nginx的497狀態碼
497 - normal request was sent to HTTPS
解釋:當網站只容許https訪問時,當用http訪問時nginx會報出497錯誤碼
思路:
利用error_page命令將497狀態碼的連接重定向到https://www.abc.org這個域名上

[root@localhost vhosts]# vim www.abc.org.conf 
server {
        listen 80;
        server_name www.abc.org abc.org;
        root /vhosts/html/www;
        index index.html index.htm index.php;
        error_page 497 https://$host$uri?$args;        //訪問www.abc.org或abc.org的http都會強制跳轉到https
        access_log logs/www.abc.org_access.log main;
        error_log logs/www.abc.org_error.log crit;

}
也能夠將80和43端口放在一塊兒
server {
        listen 443 ssl;
        listen 80;
        server_name www.abc.org abc.org;
        root /vhosts/html/www;
        index index.html index.htm index.php;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
        ssl_certificate     /usr/local/nginx/conf/cert.pem;
        ssl_certificate_key /usr/local/nginx/conf/cert.key;
        ssl_session_cache   shared:SSL:10m;
        ssl_session_timeout 10m;
        error_page 497 https://$host$uri?$args;
        location /nginx_status {
                stub_status on;
                access_log off;

        }

}

3)利用meta的刷新做用將http跳轉到https

上述的方法均會耗費服務器的資源,能夠借鑑百度使用的方法:巧妙的利用meta的刷新做用,將http跳轉到https

[root@localhost vhosts]# cat /vhosts/html/www/index.html     //修改index.html頁面
<html> 
<meta http-equiv="refresh" content="0;url=https://www.abc.org/">     //元數據刷新
welcome to www.abc.org
</html>
[root@localhost vhosts]# cat www.abc.org.conf 
server {
    listen 80;
    server_name www.abc.org abc.org;
    index index.html index.php index.htm;
    error_page 404 https://www.abc.org/;    //將404的頁面重定向到https的首頁
    access_log logs/www.abc.org_access.log main;
    error_log logs/www.abc.org_error.log crit;    
    location ~ / {
        root /vhosts/html/www;
        index index.html index.php index.htm;
    }

}
[root@localhost vhosts]# cat www.abc.org.ssl.conf 
server {
    listen 443 ssl;
    server_name www.abc.org abc.org;
    root /vhosts/html/www;
    index index.html index.htm index.php;
      ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
    ssl_certificate     /usr/local/nginx/conf/cert.pem;
    ssl_certificate_key /usr/local/nginx/conf/cert.key;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;    
    location /nginx_status {
                stub_status on;
                access_log off;

        }

}

4)經過proxy_redirec方式

[root@localhost vhosts]# cat www.abc.org.conf 
server {
    listen 80;
    server_name www.abc.org abc.org;
    index index.html index.php index.htm;
    access_log logs/www.abc.org_access.log main;
    error_log logs/www.abc.org_error.log crit;    
    proxy_redirect http:// https://;
    location ~ / {
        root /vhosts/html/www;
        index index.html index.php index.htm;
    }

}
相關文章
相關標籤/搜索