本文转自:http://www.178linux.com/14119#rd?sukey=ecafc0a7cc4a741b573a095a3eb78af6b4c9116b74d0bbc9844d8fc5e8b50b3fc807541ae53fd06c67ac4f4adaae6981

在此只是做个笔记给自己看的。

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

测试页面访问正常

实现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

转载请注明:linux运维部落 » Nginx专题: 从编译安装到URL重写

Nginx 的编译安装和URL地址重写的更多相关文章

  1. 初识Nginx及编译安装Nginx

    初识Nginx及编译安装Nginx 环境说明: 系统版本    CentOS 6.9 x86_64 软件版本    nginx-1.12.2 1.什么是Nginx? 如果你听说或使用过Apache软件 ...

  2. nginx的编译安装以及启动脚本编写

    Nginx的编译安装和启动脚本的编写 Nginxd的功能强大,可以实现代理.负载均衡等企业常用的功能.下面介绍一下nginx的编译安装方法: 1. 下载 官方下载地址:http://nginx.org ...

  3. 【01】Nginx:编译安装/动态添加模块

    写在前面的话 说起 Nginx,别说运维,就是很多开发人员也很熟悉,毕竟如今已经 2019 年了,Apache 更多的要么成为了历史,要么成为了历史残留. 我们在提及 Nginx 的时候,一直在强调他 ...

  4. nginx应用编译安装

    nginx应用编译安装: 安装编译所需依赖包: # apt-get install make gcc g++ libcurl3-openssl-dev libfreetype6-dev libmcry ...

  5. 【nginx运维基础(1)】Nginx的编译安装与使用

    nginx的官方手册: http://nginx.org/en/docs/ 编译安装 下载地址: http://nginx.org/en/download.html # 为了支持rewrite功能,我 ...

  6. Nginx服务编译安装、日志功能、状态模块及访问认证模式实操

    系统环境 [root@web ~]# cat /etc/redhat-release CentOS release 6.9 (Final) [root@web ~]# uname -a Linux d ...

  7. Nginx的编译安装及选项

    编译安装Nginx1.安装常见的工具和库(GCC.PCRE.zlib.OpenSSL) Nginx是一个由C语言编写的,所以需要一个编译工具如GNU的GCC[root@www ~]# yum inst ...

  8. centos7 yum安装nginx和 编译安装tengine

    说明 我这里给大家演示一下如何安装nginx,nginx我就不多介绍了,然后我再说一点就是,安装的两种方法都可以,编译安装和yum安装,我不能每个都演示两遍呀,所以看到我这博客的你,学会举一反三好吧? ...

  9. nginx重新编译安装upload模块

    由于php处理上传会出现超时,并且显示上传进度官方php不支持nginx+php,所以决定让nginx自己处理上传,我本地环境是mac上已经安装过nginx1.8.0,安装方式为brew,所以需要重新 ...

随机推荐

  1. 超链接a的target属性

    <a>标签的target意思很明确就是在哪里打开目标文档. 第一种情况: 默认情况:当我们没有设置超链接属性target的value值时默认是_self,即<a target=&qu ...

  2. Vim 命令整理

    1. 文件命令 2. 模式切换 3. 移动命令 4. 书签命令 5. 修改命令 6. 可视化操作 7. 区域选择 8. 宏命令 9. 分屏 10. 系统设置命令 1. 文件命令 [:]开始的命令需要输 ...

  3. AC日记——数1的个数 openjudge 1.5 40

    40:数1的个数 总时间限制:  1000ms 内存限制:  65536kB 描述 给定一个十进制正整数n,写下从1到n的所有整数,然后数一下其中出现的数字“1”的个数. 例如当n=2时,写下1,2. ...

  4. compass电子罗盘

    GPS       这个用过GPS的机油肯定不陌生.          还是 介绍一下i8000的电子罗盘.传统罗盘用一根被磁化的磁针来感应地球磁场,地球磁场与磁针之间的磁力时磁针转动,直至磁针的两端 ...

  5. Flex布局教程及属性速查

    一.Flex布局介绍 伸缩盒模型(flexbox)是一个新的盒子模型,意为"弹性布局",用来为盒状模型提供最大的灵活性,主要优化了UI布局.Flexbox的功能主要包手:简单使用一 ...

  6. 查看LINUX进程内存占用情况

    可以直接使用top命令后,查看%MEM的内容.可以选择按进程查看或者按用户查看,如想查看oracle用户的进程内存使用情况的话可以使用如下的命令: (1)top top命令是Linux下常用的性能分析 ...

  7. android studio 中 .9.png的制作

    折腾好久,最后在一个群里面咨询一个朋友才弄好的,用的是1.2.2版,感觉对.9的支持不太好, 1,用一张干净的png图片放在mipmap里面. 2,点击图片右键最后一项,create 9-patch ...

  8. Iterator遍历器 调用Symbol.Iterator属性,遍历器对象。

    Iterator实现原理 创建一个指针对象,指向当前数据结构的起始位置.也就是说,遍历器对象本质上,就是一个指针对象. 第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员. 第二次调 ...

  9. Meet Python: little notes

    Source: http://www.liaoxuefeng.com/ ❤ Escape character: '\' - '\n': newline; - '\t': tab; - '\\': \; ...

  10. 快速排名 让人疯狂的黑帽seo技术

    对于黑帽seo大家或许并不陌生,黑帽seo和白帽seo恰恰相反,是作弊手段.有白帽seo的时候,就有了黑帽seo一直到现在.但隔行如隔山这句话这句话一点都没错,再没接触黑帽seo技术之前我根本不知道黑 ...