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等包

[[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/目录中[[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;            }        }

创建对应网页文件

[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并自签证书

[[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.csrYou are about to be asked to enter information that will be incorporatedinto 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 blankFor some fields there will be a default value,If you enter ‘.‘, the field will be left blank.-----Country Name (2 letter code) [XX]:CNState or Province Name (full name) []:AHLocality Name (eg, city) [Default City]:HFOrganization Name (eg, company) [Default Company Ltd]:AnyISalIn LTDOrganizational Unit Name (eg, section) []:ops    Common Name (eg, your name or your server‘s hostname) []:www.anyisalin.comEmail Address []:webadmin.anyisalin.com

Please enter the following ‘extra‘ attributesto be sent with your certificate requestA challenge password []:An optional company name []:

签署证书

[[email protected] ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365Using configuration from /etc/pki/tls/openssl.cnfCheck that the request matches the signatureSignature okCertificate 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]yWrite out database with 1 new entriesData 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 -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: 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;        }     

}

创建对应的网页文件

[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

时间: 2024-08-05 18:24:08

Nginx专题: 从编译安装到URL重写的相关文章

Nginx 的编译安装和URL地址重写

本文转自:http://www.178linux.com/14119#rd?sukey=ecafc0a7cc4a741b573a095a3eb78af6b4c9116b74d0bbc9844d8fc5e8b50b3fc807541ae53fd06c67ac4f4adaae6981 在此只是做个笔记给自己看的. Nginx专题: 从编译安装到URL重写 前言 环境介绍 Nginx介绍 编译安装Nginx 配置文件解释 main和event{}的配置 http{}的基本配置 配置Nginx 搭建一个

nginx基础及编译安装

nginx是http服务器和反向代理服务器,又是IMAP/POP3/SMTP 代理服务器 nginx特性: 基本功能: 1.能够实现服务于静态文件,也就是静态资源的web服务器,能自动缓存打开的文件描述符: 2.反向代理服务器,能够实现简单的负载均衡和冗余 3.能够支持FastCGI协议 4.有模块化话功能,但非DSO(动态装卸载)机制,支持多种过滤器gzip,SSI和完成图像大小调整等 5.支持SSL功能 扩展功能: 1.能够基于名称和IP做虚拟主机 2.支持keepalive 3.支持平滑的

mac下Nginx+lua模块编译安装

Nginx的nb之处就不说了,lua也是一个小巧的脚本语言,由标准C编写而成,几乎可以运行在所有的平台上,也非常强大,其他特性请自行度娘.nginx_lua_module是由淘宝的工程师清无(王晓哲)和春来(章亦春)所开发的nginx第三方模块,它能将lua语言嵌入到nginx配置中,从而使用lua就极大增强了nginx的能力 http://wiki.nginx.org/HttpLuaModule 下面说说mac下Nginx如何编译集成nginx_lua_module模块 1. 下载nginx需

Nginx之一:编译安装及基础应用

一.Nginx简介 Nginx是一个轻量级的,高性能的Web服务器以及反向代理和邮箱(IMAP/POP3)代理服务器.它运行在UNIX,GNU/Linux,BSD各种版本,Mac OS X,Solaris和Windows.据统计,6%的网站使用Nginx Web服务器.Nginx是少数能处理C10K问题的服务器之一.跟传统的服务器不同,Nginx不依赖线程来处理请求.相反,它使用了更多的可扩展的事件驱动(异步)架构.Nginx为一些高流量的网站提供动力,比如WordPress,人人网,腾讯,网易

nginx学习笔记之一:nginx介绍及其编译安装

Nginx是一款高性能的web服务器.反向代理服务器及电子邮件(IMAP/POP3)代理服务器,具有占用内存少,并发能力强等优点. 一.nginx的功能与特性 1.基本功能及特性 ①作为静态资源的web服务器,能缓存打开的文件描述符: ②作为反向代理服务器,可做缓存.负载均衡: ③支持FastCGI ④模块化,非DSO机制(不能动态装卸载),过滤器gzip,SSI和图像大小调整等 ⑤支持SSL 2.扩展功能: ①基于名称和IP做虚拟主机 ②支持keepalive ③支持平滑配置更新或程序版本升级

Nginx源码编译安装选项

[Nginx源码编译过程] make是用来编译的,它从Makefile中读取指令,然后编译. make install是用来安装的,它也从Makefile中读取指令,安装到指定的位置. configure命令是用来检测你的安装平台的目标特征的.它定义了系统的各个方面,包括nginx的被允许使用的连接处理的方法,比如它会检测你是不是有CC或GCC,并不是需要CC或GCC,它是个shell脚本,执行结束时,它会创建一个Makefile文件. [Nginx的configure命令支持以下参数] --p

Nginx 源码编译安装

Nginx 源码编译安装环境 Centos7 Nginx1.8.1    下载地址:http://nginx.org/download/ 选择自己想要的版本 我这边使用1.8.1,下载地址:http://nginx.org/download/nginx-1.8.1.tar.gz 1.编译前安装环境 [[email protected]_30 ~]# yum groupinstall "Development Tools" -y                #安装开发工具包 [[ema

Nginx实践01-ngnix编译安装-测试

1.下载nginx安装包 下载地址:http://nginx.org/en/download.html(里面有nginx各个版本) 解压到指定目录: 解压出来的目录简单介绍: src:软件的所有源代码 man:man文档 auto:脚本文件,和configure脚本程序有关 conf:配置文件 html:存放了两个后缀为.html的静态页面文件 2.编译安装常用参数 --prefix=<path>:指定nginx软件的安装路径 --prefix=<path>:指定nginx可执行文

Nginx服务器上编译安装PHP

下载PHP# wget http://cn2.php.net/distributions/php-7.0.0.tar.gz 解压缩PHP# tar -zxvf php-7.0.0.tar.gz && cd php-7.0.0 安装依赖软件# yum -y install gcc libxml2-devel 编译安装PHP# ./configure --prefix=/usr/local/php7 --enable-fpm --with-fpm-user=nginx --with-fpm-g