终极移动.htaccess重定向

Dan*_*Dan 6 .htaccess mobile redirect

我已经使用下面的.htaccess代码为移动/桌面重定向提供了一个不错的工作解决方案,但是如果有人可以提供帮助,还有一些可以真正实现最终的增强功能.

目录设置:

  • 桌面网站:website.com
  • 移动网站:m.website.com

Cookie启用链接:

  • 从桌面站点移动到移动站点,设置cookie以保持在移动设备上:http://m.website.com?m = 1
  • 从移动站点到桌面站点,设置cookie以保持在桌面上:http://www.website.com?m = 0

当前.htaccess文件:

RewriteEngine on

# Check if this is the desktop to mobile query string
RewriteCond %{QUERY_STRING} (^|&)m=1(&|$)

# Set a cookie, and skip the next 2 rules 
RewriteRule ^ - [CO=mredir:1:%{HTTP_HOST},S=2]

# Check if this is the mobile to desktop query string
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)

# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]

# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST} !^m\.

# Can not read and write cookie in same request, must duplicate condition
RewriteCond %{QUERY_STRING} !(^|&)m=0(&|$) 

# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP_COOKIE} !^.*mredir=0.*$ [NC]

RewriteRule ^(.*)$ http://m.website.com/ [L,R=302]
Run Code Online (Sandbox Code Playgroud)

我想要添加的东西:

  1. 如果我们要使用移动设备或只是普通桌面访问的桌面版,请确保它始终添加www.
  2. 对于桌面到移动重定向,直接匹配移动页面,但如果不存在,则默认为移动主页.(例如:如果您在移动设备上访问website.com/chairs,它将尝试重定向到m.website.com/chairs,但如果它不存在,它将改为重定向到m.website.com.我认为映射会类似^(.*)$ http://m.website.com/$1,但不知道如何实现回退到主页

此外,如果有人注意到当前代码中的任何错误或改进,也会喜欢听到它!

Sey*_*sen 0

RewriteEngine on

# Check if this is the desktop to mobile query string
RewriteCond %{QUERY_STRING} (^|&)m=1(&|$)

# Set a cookie, and skip the next 2 rules 
RewriteRule ^ - [CO=mredir:1:%{HTTP_HOST},S=2]

# Check if this is the mobile to desktop query string
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)

# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]

# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST} !^m\.

# Can not read and write cookie in same request, must duplicate condition
RewriteCond %{QUERY_STRING} !(^|&)m=0(&|$) 

# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP_COOKIE} !^.*mredir=0.*$ [NC]

RewriteRule ^(.*)$ http://m.website.com/ [L,R=302]

# 1.) Check if on desktop site and having www., if not redirect to www.website.com
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^m\. [NC]
RewriteRule ^(.*)$ http://www.website.com$1 [R=301,L]
Run Code Online (Sandbox Code Playgroud)

2.) 这不能用 mod_rewrite 来完成,除非“/chairs”是一个现有文件(我猜它不是)。所以我会用你想要的脚本语言来检查它 - 例如在 php 中:

if (!pageexists($_GET['page']) && $_SERVER['HTTP_HOST'] == 'm.website.com')
  header("Location: http://m.website.com/");
Run Code Online (Sandbox Code Playgroud)

其中 pageexists() 是您定义的函数,用于检查移动版本中是否有该页面的内容。