Nginx区分PC或手机访问不同域名

经过一系列的审核,耗时近一个月的网站备案终于通过,便迫不及待地进行了域名解析。需要分别对PC和手机进行配置,具体如下。

一、需求

客户端 域名 描述 访问目录
PC端 www.harriszhang.cn 用于PC端访问 /var/www/space/space/index.html
手机端 m.harriszhang.cn 用于移动端访问 /var/www/space/spaceMobile/index.html

当在PC端访问www.harriszhang.cnm.harriszhang.cn时,跳转到www.harriszhang.cn

当在移动端访问www.harriszhang.cnm.harriszhang.cn时,跳转到m.harriszhang.cn

二、Nginx配置

2.1 PC访问配置

修改前:

server {
    listen       80;
    server_name  localhost;

    location / {
        root /var/www/space/space;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    ...
}

修改后:

server {
    listen       80;
    server_name  www.harriszhang.cn;

    if ($http_host !~ "www.harriszhang.cn$") {
        rewrite ^(.*) http://www.harriszhang.cn$1 permanent;
    }
    if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
        rewrite ^(.*) http://m.harriszhang.cn$1 permanent;
    }

    location / {
        root /var/www/space/space;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    ...
}

2.2 移动端访问配置

修改前:

server {
    listen       80;
    server_name  localhost;

    location / {
        root /var/www/space/spaceMobile;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    ...
}

修改后:

server {
    listen       80;
    server_name  m.harriszhang.cn;

    if ($http_user_agent !~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
        rewrite ^(.*) http://www.harriszhang.cn$1 permanent;
    }

    location / {
        root /var/www/space/spaceMobile;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    ...
}

三、重启Nginx

通过nginx -s reload命令重新启动 Nginx,即可看到设置已经生效。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容