nginx 地址重写 rewrite

2019-10-11  本文已影响0人  Oooyzx
变量名称 变量说明
$args 这个变量等于请求行中的参数,同$query_string
$content_length 请求头中的Content-length字段
$content_type 请求头中的Content-Type字段
$document_root 当前请求在root指令中指定的值
$host 请求主机头字段,否则为服务器名称
$http_user_agent 客户端agent信息
$http_cookie 客户端cookie信息
$limit_rate 这个变量可以限制连接速率
$request_method 客户端请求的动作,通常为GET或POST
$remote_addr 客户端的IP地址
$remote_port 客户端的端口
$remote_user 已经经过Auth Basic Module验证的用户名
$request_filename 当前请求的文件路径,由root或alias指令与URI请求生成
$scheme HTTP方法(如http,https)
$server_protocol 请求使用的协议,通常是HTTP/1.0或HTTP/1.1
$server_addr 服务器地址,在完成一次系统调用后可以确定这个值
$server_name 服务器名称
$server_port 请求到达服务器的端口号
$request_uri 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”
$uri 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”
$document_uri 与$uri相同

例:http://www.xxx.com:88/test1/test2/test.php

$host:www.xxx.com  #localhost 域名
$server_port:88    #端口号
$request_uri:http://www.xxx.com:88/test1/test2/test.php  #完整url
$document_uri:/test1/test2/test.php    #端口号后的url路径
$document_root:/var/www/html           #实体文件所在的根路径
$request_filename:/var/www/html/test1/test2/test.php    #实体文件所在的绝对路径

==============================================================

-nginx 地址重写 rewrite实验:

例1 : 输入域名 重写至 京东官网(可自定义域名和跳转网页)

#http://www.tianyun.com/ccc/1.html ==> http://jd.com/ccc/1.html

ifconfig enp0s25:5 10.0.13.200

ifconfig可查看配置情况:

配置虚拟ip
# 将虚拟ip 配置自定义域名www.tianyun.com中

10.0.13.200 www.tianyun.com
vim rewrite.conf            #创建rewrite.conf文件
server {
   listen       10.0.13.200:80;
   server_name  localhost;
   #charset koi8-r;
   #access_log   /var/log/nginx/host.access.log
   location / {      #根目录为主页
      root   /usr/share/nginx/html;
      index index.html;
 }
   if ( $host ~* www.tianyun.com ) {   #当正则匹配到www.tianyun.com时重写至京东首页
      rewrite .* http://jd.com$request_uri permanent;
      # return 301 http://jd.com$request_uri;

 }
}
  systemctl restart nginx
跳转.png
例2: 用户解析:

#http://alice.tianyun.com ==> http://www.tianyun.com/alice
#http://jack.tianyun.com ==> http://www.tianyun.com/jack

mkdir jack alice

echo jack.... > jack/index.html
echo alice... > alice/index.html
    if ($host ~* "^www.tianyun.com$" ) {
       break;
    }  
    if ($host ~* "^(.*)\.tianyun\.com$" ) {
       set $user $1;
       rewrite .* http://www.tianyun.com/$user permanent;
    }

  systemctl restart nginx

注意:有可能报错 无法解析,报错如下:

解析不了.png
原因可能是:在/etc/hosts 下没有添加用户的域名解析
10.0.13.200 alice.tianyun.com
10.0.13.200 jack.tianyun.com
用户的域名解析.png

==============================================================

拓展题:

(后续空闲再更新完整操作实验版本)

注意:

[root@localhost html]# mkdir test
[root@localhost html]# echo 'break' > test/break.html
[root@localhost html]# echo 'last' > test/last.html
[root@localhost html]# echo 'test...' > test/test.html
image.png
上一篇 下一篇

猜你喜欢

热点阅读