douquan1953
2015-03-06 16:30
浏览 93
已采纳

.htaccess仅在GET参数存在时重定向

I have a client with an old website without 'pretty' URLs. So currently it looks like this:

http://www.domain.com/?w=42&a=5&b=3

The parameter values are numbers only.

Now they want to move the old site to a subdomain and main (www) domain would be home to a new website (WP with SEO friendly URLs).

Now what I would like to do is redirect all requests that come to the /?w=<num> (and ONLY those) to sub.domain.com/?w=<num>, so that existing links (mostly from Google) get redirected to the subdomain page, while the new page works serving new content thorough pretty URLs.

I tried this:

# This works, but redirects the entire www.domain.com
# to sub.domain.com no mather what 
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://sub.domain.com/$1 [R=301,L]

# But this DOESN'T work
RewriteRule   ^/?w(.*)  http://sub.domain.com/?w$1  [R=301,L]

# Also tried to redirect 'by hand', but DIDN'T work either
Redirect 301 /?w=42 http://sub.domain.com/?w=42 

What am I doing wrong? I searched high and low but always end up with this kind of suggestions. Or maybe I'm just searching for wrong keywords ...

Thank you!

图片转代码服务由CSDN问答提供 功能建议

我的客户端有一个没有“漂亮”网址的旧网站。 所以目前它看起来像这样:

  http://www.domain.com/?w=42&a=5&b=3
  <  / pre> 
 
 

参数值仅为数字。

现在,他们希望将旧网站移动到子域,而主(www)域将是 新网站(WP与SEO友好的URL)。

现在我想要做的是将所有来自 /?w =&lt; num&gt; (仅限那些)的请求重定向到 sub.domain.com/?w=<num> ,以便现有链接(主要来自Google)被重定向到子域名页面,而新页面可以通过漂亮的URL提供新内容。

我试过这个:

 #这有效,但重定向整个www.domain.com 
#到sub.domain.com没有其他什么 
RewriteCond%{HTTP_HOST} ^ www \ .domain \ .com $ [NC] 
RewriteRule ^(。*)$ http://sub.domain.com/$1 [R = 301,L] 
 
#但是 这不起作用
RewriteRule ^ /?w(。*)http://sub.domain.com/?w$1 [R = 301,L] 
 
#还尝试重定向“手动”,但 不能正常工作
Redirect 301 /?w = 42 http://sub.domain.com/?w=42 
   
 
 

我做错了什么? 我搜索得很高,但总是得到这样的建议。 或者我可能只是在寻找错误的关键词...

谢谢!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dszm02606009 2015-03-06 17:27
    已采纳

    You can't match against the query string inside a rewrite rule or a redirect directive. You need to match against the %{QUERY_STRING} variable. Try:

    RewriteCond %{QUERY_STRING} (^|&)w=[0-9]+(&|$)
    RewriteRule ^(.*)$ http://sub.domain.com/$1 [L,R=301]
    

    Note that the query string gets automatically appended to the end of the rule's destination.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongshi3818 2017-09-14 11:08

    Just for documentation: If you want to redirect one directory (path) only if there is a URL parameter present, from one path to another, while maintaining the URL parameter, you can use this in your htaccess file:

    # /programs/?id=1 to new path /loadprog/?id=1
    RewriteCond %{REQUEST_URI} ^/programs/
    RewriteCond %{QUERY_STRING} id=
    RewriteRule ^programs\/$ /loadprog/$1 [R=301,L]
    

    I am sure this will help others since I stumbled over the question above trying to find this answer.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题