【问题标题】:How to redirect to clean URL (remove query string from URL) with RewriteRule in .htaccess如何使用 .htaccess 中的 RewriteRule 重定向到干净的 URL(从 URL 中删除查询字符串)
【发布时间】:2013-09-22 07:28:34
【问题描述】:

设置cookie后访问www.example.com?mobile=0时如何重定向到www.example.com

<IfModule mod_rewrite.c>
RewriteBase /
RewriteEngine On

# Check if mobile=1 is set and set cookie 'mobile' equal to 1
RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

# Check if mobile=0 is set and set cookie 'mobile' equal to 0
RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

# cookie can't be set and read in the same request so check
RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
RewriteRule ^ - [S=1]

# Check if this looks like a mobile device
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
RewriteCond %{HTTP:Profile}       !^$

# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://m.example.com%{REQUEST_URI} [R,L]
</IfModule>

如果从移动设备访问,此代码的作用是将www.example.com 重定向到m.example.com,但在访问www.example.com?mobile=0 时不会重定向,这将设置一个cookie,以使用户即使在移动设备上也能留在主站点上。

一旦设置了阻止重定向的 cookie,我想添加一个从 www.example.com?mobile=0 到干净 URL www.example.com 的 302 重定向。

【问题讨论】:

    标签: apache .htaccess redirect mod-rewrite http-status-code-302


    【解决方案1】:

    将此规则附加到现有规则的末尾:

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+\?mobile=0[\s&] [NC]
    RewriteRule ^ /? [R=302,L]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2021-08-18
      相关资源
      最近更新 更多