同一个网站可能有pc跟移动端,需要根据客户端来重定向到适配的页面,例如移动访问的时候就展示移动端,pc端访问的时候就展示pc端
目前有几个方案
同一域名 重新定位root目录
location / {
root /data/wwwroot/pc;
#如果是移动端,则定位到移动端根目录
if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {
root /data/wwwroot/mobile;
}
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
不同域名 通过重定向
if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {
rewrite ^/(.*)$ https://mobile.com$uri redirect; // redirect表示302跳转(暂时性转移)
}
万能方案
移动端起一个server 默认访问都是pc端,如果检测到移动端用proxy_pass实现
location / {
# ...
#如果是移动端,则定位到移动端根目录
if ($http_user_agent ~* "(mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)") {
proxy_pass http://127.0.0.1:8888;
}
}
#另起的移动端server
server
{
listen 8888;
server_name 127.0.0.1;
index index.html;
root /data/wwwroot/mobile;
location /nginx_status
{
stub_status on;
access_log off;
}
location / {
try_files $uri $uri/ @router;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*.(js|css)?$
{
expires 12h;
}
location ~ /.well-known {
allow all;
}
location ~ /.
{
deny all;
}
access_log /home/wwwlogs/access.log;
error_log /home/wwwlogs/nginx_error.log;
}
\