linux-nginx-地址重定向

ngx_http_rewrite_module 模块指令

return 指令

return code; #返回给客户端指定的HTTP状态码
return code [text]; #返回给客户端的状态码及响应报文的实体内容,可以调用变量,其中text如果有空格,需要用单或双引号
return code URL; #返回给客户端的URL地址

rewrite flag 使用介绍

利用nginx的rewrite的指令,可以实现url的重新跳转,rewrtie有四种不同的flag,分别是redirect(临时 重定向302)、permanent(永久重定向301)、break和last。其中前两种是跳转型的flag,后两种是代理型

  • 跳转型指由客户端浏览器重新对新地址进行请求
  • 代理型是在WEB服务器内部实现跳转

flag 说明

复制代码
redirect;
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302


permanent; #重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求,状态码:301

break; #重写完成后,停止对当前URL在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使用 #适用于一个URL一次重写
last; #重写完成后,停止对当前URI在当前location中后续的其它重写操作,而后对新的URL启动新一轮重写检查,不建议在location中使用 #适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户
复制代码

 

实现地址重定向

nginx配置文件

复制代码
server {
  listen 80;
  server_name www.lyj.org;
  location / {
    root /data/nginx/html/pc;
    #return 301 http://www.baidu.com;
    #rewrite / http://www.baidu.com redirect;
  }
}
复制代码

返回结果

[root@data-server ~]#curl www.lyj.org
pc  web

 

 return,返回新的url地址

复制代码
server {
  listen 80;
  server_name www.lyj.org;
  location / {
    root /data/nginx/html/pc;
    return 301 http://www.baidu.com;
    #rewrite / http://www.baidu.com redirect;
  }
}
复制代码

测试

复制代码
[root@data-server ~]#curl www.lyj.org
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
[root@data-server ~]#curl www.lyj.org -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.20.2
Date: Fri, 10 Jun 2022 13:37:09 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.baidu.com
复制代码

 

 reworite 地址重定向

复制代码
server {
  listen 80;
  server_name www.lyj.org;
  location / {
    root /data/nginx/html/pc;
    #return 301 http://www.baidu.com;
    rewrite / http://www.baidu.com redirect;  #临时重定向
  }
}
复制代码

 

复制代码
[root@data-server ~]#curl www.lyj.org 
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
[root@data-server ~]#curl www.lyj.org -I
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.20.2
Date: Fri, 10 Jun 2022 13:38:49 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: http://www.baidu.com
复制代码

 

posted @   goodbay说拜拜  阅读(522)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示