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

精彩介紹

  • 前言

  • 環境介紹

  • Nginx介紹

  • 編譯安裝Nginx

  • 配置文件解釋

  • 配置Nginx

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

  • 總結

前言

本文主要實現使用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。

Advertisements

編譯安裝Nginx

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

[[email protected] ~]# yum groupinstall "Development Tools" "Server Platform Development" #安裝包組

[[email protected] ~]# yum install pcre-devel openssl-devel zlib-devel -y #安裝相應軟體

[[email protected] ~]# tar xf nginx-1.6.1.tar.gz -C /usr/src/ #解壓nginx源碼包到/usr/src/目錄中

Advertisements

[[email protected] ~]# cd /usr/src/

[[email protected] src]# cd nginx-1.6.1/

[[email protected] nginx-1.6.1]# groupadd -r nginx #創建組

[[email protected] nginx-1.6.1]# useradd -r -g nginx nginx #創建用戶

[[email protected] 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

#關於編譯選項的參數含義,請查閱官方文檔

[[email protected] 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;

}

}

創建對應網頁文件

[[email protected] /]# mkdir htdocs/html -pv #創建文件夾

mkdir: created directory `htdocs'

mkdir: created directory `htdocs/html'

[[email protected] /]# cd htdocs/html/

[[email protected] html]# echo "<h1>www.anyisalin.com</h1>" >> index.html #創建網頁文件

[[email protected] html]# echo "Sorry, Page Not Found" > 404.html #創建404頁面

[[email protected] html]# nginx -t #檢查配置文件語法

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[[email protected] html]# nginx #啟動nginx

測試頁面訪問正常

實現https

創建CA並簽署Nginx證書

這裡對於openssl的操作不做解釋, 有興趣可以看我以前的文章

創建私有CA並自簽證書

[[email protected] html]# cd /etc/pki/CA

[[email protected] CA]# (umask 077; openssl genrsa -out private/cakey.pem 2048)

[[email protected] 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

[[email protected] CA]# touch serial index.txt

[[email protected] CA]# echo 01 > serial

創建nginx證書

[[email protected] CA]# cd /etc/nginx/

[[email protected] nginx]# mkdir ssl

[[email protected] nginx]# cd ssl/

[[email protected] ssl]# (umask 077; openssl genrsa -out nginx.key 1024)

Generating RSA private key, 1024 bit long modulus

..++++++

.............................................................................................++++++

e is 65537 (0x10001)

[[email protected] 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 []:

簽署證書

[[email protected] 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

重載服務進行測試

[[email protected] ssl]# nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[[email protected] ssl]# nginx -s reload

未導入證書前

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

實現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

針對用戶代理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;

}

}

創建對應的網頁文件

[[email protected] /]# mkdir /htdocs/html/{Chrome,IE,Moblie}

[[email protected] /]# echo "Welecom Moblie" > /htdocs/html/Moblie/index.html

[[email protected] /]# echo "Welecom Chrome" > /htdocs/html/Chrome/index.html

[[email protected] /]# echo "Welecom IE" > /htdocs/html/IE/index.html

測試

手機

chrome

總結

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

Advertisements

你可能會喜歡