图图
发布于 2023-10-11 / 106 阅读 / 0 评论 / 0 点赞

nginx一个域名根据客户端类型分发web或移动客户端

网站web和mobile不是自适应的情况下,想要同一个域名来访问两个客户端,nginx可以通过获取http_user_agent来判断,分发不同的资源,配置下代码

server {
    listen 443 ssl;
    listen 80;
    server_name xx.xx.com;

    ssl_certificate   /etc/nginx/ssl/xx.com.pem;
    ssl_certificate_key  /etc/nginx/ssl/xx.com.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    if ($scheme = http) {
        return  301 https://$host$request_uri;
    }

    location / {
        root /usr/share/nginx/html/web/dist;
        
        if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {
            root /usr/share/nginx/html/mobile/dist;
        }

        try_files $uri $uri/ /index.html;
        index  index.html index.htm;
    }
}