Nginx專題: 從編譯安裝到URL重寫

Nginx專題: 從編譯安裝到URL重寫

前言

本文主要實現使用Nginx作為Web服務器, 并使用URL Rewrite實現將手機對Web站點的請求專門重寫到一個專門為手機定制的Web頁面中

環境介紹

筆者只有一臺虛擬機, 橋接到室內的路由器便于手機進行訪問, IP地址為192.168.1.103

Nginx介紹

engine x發音同Nginx, 作者是Igor Sysoev,是目前世界上占有率第三的Web服務器軟件. Nginx是一款輕量級的Web服務器,可實現反向代理,URL rewrite等功能。Nginx擁有消耗內存小、可支持高并發連接達5W個、還支持熱部署、高性能的網絡IO模型等特性。淘寶還基于Nginx進行二次研發出Tengine

編譯安裝Nginx

需要安裝Development ToolsServer Platform Development包組和zlib-devel, pcre-devel, openssl-devel等包

[root@server1 ~]# yum groupinstall "Development Tools" "Server Platform Development" #安裝包組
[root@server1 ~]# yum install pcre-devel openssl-devel zlib-devel -y   #安裝相應軟件
[root@server1 ~]# tar xf nginx-1.6.1.tar.gz  -C /usr/src/  #解壓nginx源碼包到/usr/src/目錄中
[root@server1 ~]# cd /usr/src/
[root@server1 src]# cd nginx-1.6.1/
[root@server1 nginx-1.6.1]# groupadd -r nginx   #創建組
[root@server1 nginx-1.6.1]# useradd -r -g nginx nginx   #創建用戶
[root@server1 nginx-1.6.1]# ./configure --prefix=/usr/src/nginx --sbin-path=/sbin/ --conf-path=/etc/nginx/nginx.conf --with-http_ssl_module --user=nginx --group=nginx --with-http_gzip_static_module
   #關于編譯選項的參數含義,請查閱官方文檔
[root@server1 nginx-1.6.1]# make && make install

配置文件解釋

關于Nginx的一些工作原理我們這里不做解釋,但是我們解釋一下Nginx的配置文件中常用選項的意思 
nginx的主配置文件是nginx.conf,配置文件的位置隨著編譯的配置選項而定,我們這里是/etc/nginx/nginx.conf文件

Nginx作為web服務器時主配置文件一般分為三段, main和event{}, http{}、我們分別進行介紹

main和event{}的配置

運行相關的配置
   user User_Name [Group_name];  #運行Nginx進程的用戶和組. 默認為nobody
   error_log /path/to/error_log;  #是否啟用錯誤日志,并指定錯誤日志的存放位置, 可指定為相對路徑
   error_log /path/to/error_log notice;  #指定錯誤日志的記錄的級別
   pid /path/to/pidfile; #指定守護進程pid文件的位置  

性能相關的配置
   worker_processes number;   #運行的worker進程的個數, 默認為1    
   worker_cpu_affinity cpumask ...; #定義worker進程和cpu的綁定, 這里不做過多介紹, 不了解的可自行查找
   time_resolution interval ; 計數器的解析度,記錄日志時時間的精確性
   worker_priority number; #worker進程的優先級

事件相關的配置
   accept_mutex on|off;   #master進程調度用戶請求至worker進程的算法,輪詢和隨機. on表示輪詢
   use [epoll|rtsing|select|poll];   #指明使用的事件驅動模型
   worker_connections number; 指明一個worker進程能夠接受的最大請求書

http{}的基本配置

    1. server{}: 定義一個虛擬主機
       示例:
           server {
               listen 80;
               server_name www.anyisalin.com;
               root "/htdocs/www"
               }
   2. listen
       語法: listen address[:port];
       示例:
           listen 127.0.0.1:8000;
           listen 127.0.0.1;
           listen 8000;
           listen *:8000;
           listen localhost:8000;          
   3. server_name
       語法: server_name name...;
       支持通配符:
           匹配順序:
               1. 精確匹配        
               2. 從左向右匹配通配符   *.anyisalin.com
               3. 從右向左匹配通配符   anyisalin.*
               4. 匹配正則表達式      ~^*\.anyisalin\.com$
               5. default_server

   4. root
       語法: root path;

   5. location
       語法: location [=] [~] [~*] [^~] URL {...}
       功能:根據用戶請求的URI來匹配定義的location
           =: 精確匹配檢查
           ~: 正則表達式匹配
           ~*: 正則表達式匹配, 不區分大小寫
           ^~: URI的前半部分匹配, 不支持正則表達式

           示例:
               server {
                   listen 80;
                   server_name www.anyisalin.com;
                   location / {
                       root "/htdocs/www";
                       }      
                   location /imgs/ {
                       root "/htdocs/imgs"
                       }
                   location ~* \.php$ {
                       root "/htdocs/php"
                       }
                   }

配置Nginx

搭建一個基本的Nginx Web服務器

編輯Nginx配置文件效果如下

 server {
     listen       80;
       server_name  www.anyisalin.com;

       location / {
           root   /htdocs/html;
           index  index.html index.htm;
           error_page 404 =200 404.html;
           }
       }

創建對應網頁文件

[root@server1 /]# mkdir htdocs/html -pv     #創建文件夾
   mkdir: created directory `htdocs'
   mkdir: created directory `htdocs/html'

[root@server1 /]# cd htdocs/html/
[root@server1 html]# echo "<h1>www.anyisalin.com</h1>" >>  index.html   #創建網頁文件
[root@server1 html]# echo "Sorry, Page Not Found" > 404.html    #創建404頁面
[root@server1 html]# nginx -t   #檢查配置文件語法
   nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
   nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@server1 html]# nginx  #啟動nginx

測試頁面訪問正常

blob.png

blob.png

實現https

創建CA并簽署Nginx證書

這里對于openssl的操作不做解釋, 有興趣可以看我以前的文章: AnyISalIn的文章

創建私有CA并自簽證書

[root@server1 html]# cd /etc/pki/CA
[root@server1 CA]# (umask 077; openssl genrsa -out private/cakey.pem 2048)
[root@server1 CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 7300
   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]:CN
   State or Province Name (full name) []:AH
   Locality Name (eg, city) [Default City]:HF
   Organization Name (eg, company) [Default Company Ltd]:AnyISalIn LTD
   Organizational Unit Name (eg, section) []:ops
   Common Name (eg, your name or your server's hostname) []:www.anyisalin.com
   Email Address []:webadmin.anyisalin.com

[root@server1 CA]# touch serial index.txt
[root@server1 CA]# echo 01 > serial

創建nginx證書

[root@server1 CA]# cd /etc/nginx/
[root@server1 nginx]# mkdir ssl
[root@server1 nginx]# cd ssl/
[root@server1 ssl]# (umask 077; openssl genrsa -out nginx.key 1024)
Generating RSA private key, 1024 bit long modulus
..++++++
.............................................................................................++++++
e is 65537 (0x10001)
[root@server1 ssl]# openssl req -new -key nginx.key -out nginx.csr
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]:CN
State or Province Name (full name) []:AH
Locality Name (eg, city) [Default City]:HF
Organization Name (eg, company) [Default Company Ltd]:AnyISalIn LTD
Organizational Unit Name (eg, section) []:ops    
Common Name (eg, your name or your server's hostname) []:www.anyisalin.com
Email Address []:webadmin.anyisalin.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

簽署證書

[root@server1 ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
       Serial Number: 1 (0x1)
       Validity
           Not Before: Apr  4 13:57:02 2016 GMT
           Not After : Apr  4 13:57:02 2017 GMT
       Subject:
           countryName               = CN
           stateOrProvinceName       = AH
           organizationName          = AnyISalIn LTD
           organizationalUnitName    = ops
           commonName                = www.anyisalin.com
           emailAddress              = webadmin.anyisalin.com
       X509v3 extensions:
           X509v3 Basic Constraints:
               CA:FALSE
           Netscape Comment:
               OpenSSL Generated Certificate
           X509v3 Subject Key Identifier:
               A3:68:8D:FD:49:FD:08:1B:E3:09:45:9F:3B:48:35:1E:0F:38:C4:92
           X509v3 Authority Key Identifier:
               keyid:26:2E:FE:F6:52:41:DC:2F:C6:C1:4F:19:A0:BE:F6:14:99:93:54:4B

Certificate is to be certified until Apr  4 13:57:02 2017 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

修改配置文件

    server {
       listen       443 ssl;
       server_name  www.anyisalin.com;
       ssl_certificate      /etc/nginx/ssl/nginx.crt;
       ssl_certificate_key  /etc/nginx/ssl/nginx.key;


       location / {
           root   /htdocs/html;
           index  index.html index.htm;
           error_page 404 =200 404.html;
           }

       }

測試https

重載服務進行測試

[root@server1 ssl]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@server1 ssl]# nginx -s reload

未導入證書前

blob.png

導入證書后,因為chrome自身問題認為證書不可靠,但是已經成功

blob.png

實現URL Rewrite將不同瀏覽器的請求響應不同頁面

URL重寫的相關配置選項

    語法:rewrite regex replacement flag;

   例如:
       rewrite ^/images/(.*\.jpg)$ /img/abc/$1 break;

   效果:
       http://www.anyisalin.com/images/1.jpg --> http://www.anyisalin.com/img/abc/1.jpg

   flag:
       last: 被重寫完后不會繼續匹配下面的rewrite規則, 由User_agent重新發起對新URL的請求, 但是會重新匹配rewrite規則
       break:被重寫后不會繼續匹配下面的rewrite規則, 由User_agent重新發起對新URL的請求, 但是不會繼續匹配
       redirect:以302(臨時重定向)返回新的URL
       permanent:以301(永久重定向)返回新的URL

分析日志查看相應用戶代理的類型

blob.png

blob.png

針對用戶代理URL Rewrite

修改location為如下配置

location / {
root   /htdocs/html;
index  index.html index.htm;
error_page 404 =200 404.html;

      if ($http_user_agent ~* Android) {        #匹配到User_Agent包含Android跳轉到/Moblie中
      rewrite ^(.*)$ /Moblie/$1 break;
       }

     if ($http_user_agent ~* Chrome) {         #匹配到User_Agent包含chrome跳轉到/Chrome中
     rewrite ^(.*)$ /Chrome/$1 break;
       }

     if ($http_user_agent ~* MSIE) {          #匹配到User_Agent包含MSIE跳轉到/IE中
     rewrite ^(.*)$ /IE/$1 break;
       }    

}

創建對應的網頁文件

[root@server1 /]# mkdir /htdocs/html/{Chrome,IE,Moblie}
[root@server1 /]# echo "Welecom Moblie" > /htdocs/html/Moblie/index.html
[root@server1 /]# echo "Welecom Chrome" > /htdocs/html/Chrome/index.html
[root@server1 /]# echo "Welecom IE" > /htdocs/html/IE/index.html

測試

手機

blob.png

chrome

blob.png 
IE

blob.png

總結

這次主要簡單介紹了一下Nginx作為Web服務器的簡單使用方法,和針對不同用戶代理進行跳轉,過幾天我還會寫Nginx作為代理服務器的相關文章,敬請期待! 
作者:AnyISalIn QQ: 1449472454 
感謝:MageEdu

原創文章,作者:Net18-AnyISalIn,如若轉載,請注明出處:http://www.www58058.com/14119

(1)
Net18-AnyISalInNet18-AnyISalIn
上一篇 2016-04-04
下一篇 2016-04-05

相關推薦

  • shell 腳本之數組 和 yum 【下】

    shell 腳本之數組 和 yum 【下】 數組 ?  變量:存儲單個元素的內存空間 ?  數組:存儲多個元素的連續的內存空間,相當于多個變量的 集合。 ?  數組名和索引        索引:編號從0開始,屬于數值索引        注意:索引可支…

    Linux干貨 2016-08-24
  • corosync的高可用——高可用mariadb數據庫

    corosync, pacemaker,nfs高可用mariadb 實驗環境: 4臺CentOS 7 的主機,并關閉的iptalbes和selinux功能 主機1:10.1.43.101 node1 corosync+pacemaker+amp 主機2:10.1.43.102 node2 corosync+pacemaker+amp 主機3:10.1.43.…

    Linux干貨 2016-11-24
  • Linux任務計劃命令及應用

    at命令,crontab命令

    2018-03-12
  • 定制SecureCRT配色

    定制SecureCRT配色 SecureCRT默認的配色方案不怎么喜歡,結合網上其他人的總結+自己的探索,總結怎樣定制自己的配色。配出自己喜歡的界面,還是會很有成就感的。 使用SecureCRT自帶主題 效果圖 圖中個文件的類型: compress.tar.gz 壓縮文件 directory 目錄 file.txt 普通文件&n…

    Linux干貨 2017-09-03
  • 在CentOS中獲取命令幫助

    在CentOS中獲取命令幫助    在使用和學習CentOS系統中,當我們遇上不熟悉的命令卻又需要了解它的詳細用法的時候,我們需要獲取幫助。除了借助他人和搜索引擎之外,自己通過查看系統幫助文檔來解決問題是很重要的。下面就來介紹如何獲取幫助以及簡單的解決思路:    一、如何獲取命令幫助 Linux提供多層次的命令幫助:…

    Linux干貨 2016-07-27
  • 馬哥教育21期網絡班—第12周課程+練習—-LAMP練習

    1、請描述一次完整的http請求處理過程; (1) 建立或處理連接:接收請求或拒絕請求 (2) 接收請求: 接收來自于網絡的請求報文中對某資源的一次請求的過程; 持久連接:接收到請求不會斷開這個請求 非持久連接:一個連接請求斷開一次 并發訪問響應模型(Web I/O): 單進程I/O結構:啟動一個進程處理用戶請求,而且一次只處理…

    Linux干貨 2016-09-26
欧美性久久久久