Nginx之rewrite配置域名跳转

4,474 阅读1分钟

ps:每次修改配置后,需要重启 Nginx。
命令:systemctl restart nginx
Nginx 的配置文件:/etc/nginx/nginx.conf


1.语法格式

  • rewrite 作用:将某个 URL 重写为特定的 URL。
  • 语法格式:rewrite(关键字) <regex>(正则表达式) <replacement>(替代内容)。
  • 根据 正则表达式 重定向到 replacement

2.对 a 域名的访问全部 redirect 到 b 域名

  • 配置前 server 中不允许存在 location / { ... }
  • 配置示例:
location / {
    rewrite ^/(.*) http://1000.xidian.edu.cn/$1;
}

  • 通过 location / 匹配所有以 / 开头的请求(即所有请求)。
  • rewrite 为固定关键字 。
  • regex 部分表示匹配完整的域名和之后的路径。
  • replacement 部分中的 $1 取自 regex 部分 ( ) 中的内容。
  • 即 nginx 将 a.com/ 之后的路径拼接到了 http://1000.xidian.edu.cn/ 后。

3.对 a 域名的不同访问 redirect 到不同域名

①应用场景

  • 同一个域名下的不同 URL 需要跳转到不同的域名下。

②示例一

location /xiaoyuan/ {
    rewrite ^/xiaoyuan(.*) http://ehall.xidian.edu.cn$1;
}
  • 跳转前:http://a.com/xiaoyuan/jwapp/sys/cjcx
  • 跳转后:

  • 通过 location /xiaoyuan/ 匹配所有以 /xiaoyuan/ 开头的请求。
  • rewrite 为固定关键字 。
  • regex 部分表示匹配完整的域名和之后的路径。
  • replacement 部分中的 $1 取自 regex 部分 ( ) 中的内容。
  • 即 nginx 将 a.com/xiaoyuan 之后的路径拼接到了 http://ehall.xidian.edu.cn 后。

③示例二

location /houqin/ {
    rewrite ^/houqin(.*) http://1000.xidian.edu.cn$1;
}
  • 跳转前:http://a.com/houqin/index.php/Request/...
  • 跳转后:

  • 通过 location /houqin/ 匹配所有以 /houqin/ 开头的请求。
  • rewrite 为固定关键字。
  • regex 部分表示匹配完整的域名和之后的路径。
  • replacement 部分中的 $1 取自 regex 部分 ( ) 中的内容。
  • 即 nginx 将 a.com/houqin 之后的路径拼接到了 http://1000.xidian.edu.cn 后。

附录