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 Tools
和Server 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
測試頁面訪問正常
實現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
未導入證書前
導入證書后,因為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;
}
}
創建對應的網頁文件
[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
測試
手機
chrome
IE
總結
這次主要簡單介紹了一下Nginx作為Web服務器的簡單使用方法,和針對不同用戶代理進行跳轉,過幾天我還會寫Nginx作為代理服務器的相關文章,敬請期待!
作者:AnyISalIn QQ: 1449472454
感謝:MageEdu
原創文章,作者:Net18-AnyISalIn,如若轉載,請注明出處:http://www.www58058.com/14119