首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >12.9 Nginx域名重定向

12.9 Nginx域名重定向

作者头像
运维小白
发布2018-02-06 15:56:35
8.1K0
发布2018-02-06 15:56:35
举报
文章被收录于专栏:运维小白运维小白

Nginx域名重定向目录概要

  • 更改test.com.conf
server
{
    listen 80;
    server_name test.com test1.com test2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
}
  • server_name后面支持写多个域名,这里要和httpd的做一个对比
  • permanent为永久重定向,状态码为301,如果写redirect则为302

Nginx域名重定向

  • 在Nginx里“server_name” 支持跟多个域名;但是Apache“server_name”只能跟一个域名,需要跟多个域名,需要使用Alisa;
  • 在Nginx的conf配置文件里“server_name ” 设置了多个域名,就会使网站的权重变了,到底需要哪个域名为主站点,所以需要域名重定向
  1. 修改配置文件vim /usr/local/nginx/conf/vhost/test.com.conf,(这里删除用户认证那一块代码)
[root@hf-01 vhost]# vim test.com.conf

server
{
    listen 80;
    server_name test.com test1.com test2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
}
保存退出
  • if ($host != ‘test.com’ ) //假如域名,“!=”不等于 test.com,将执行下面的脚本
  • rewrite ^/(.)$ http://test.com/$1 permanent; // ^/(.)$ 正式写法 http://$host/(.*)$ 这段可以直接省略掉的,同时还可以加上一些规则,
  • permanent 就是301的意思
  • 如果想弄成302,只需要更改为 redirect
  1. 检查配置文件语法错误,并重新加载配置文件
[root@hf-01 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@hf-01 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@hf-01 vhost]# 
  1. 测试,用test2.com去访问,会看到显示301,给它重定向到了http://test.com/index.html
[root@hf-01 vhost]# curl -x127.0.0.1:80 test2.com/index.html -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 22:23:52 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.html

[root@hf-01 vhost]# 
  1. 定义一个不同的网址再来测试访问
[root@hf-01 vhost]# curl -x127.0.0.1:80 test2.com/admin/index.html -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 22:25:57 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/admin/index.html

[root@hf-01 vhost]# 
  1. 它会访问默认虚拟主机
  2. 这时若是随意访问一个不存在的网址,则会显示404
[root@hf-01 vhost]# curl -x127.0.0.1:80 hanfeng.com/admin/index.html -I
HTTP/1.1 404 Not Found
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 22:27:37 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

[root@hf-01 vhost]# 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Nginx域名重定向目录概要
  • Nginx域名重定向
相关产品与服务
轻量应用服务器
轻量应用服务器(TencentCloud Lighthouse)是新一代开箱即用、面向轻量应用场景的云服务器产品,助力中小企业和开发者便捷高效的在云端构建网站、Web应用、小程序/小游戏、游戏服、电商应用、云盘/图床和开发测试环境,相比普通云服务器更加简单易用且更贴近应用,以套餐形式整体售卖云资源并提供高带宽流量包,将热门开源软件打包实现一键构建应用,提供极简上云体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档