Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

apache - Redirect only if came from another domain

I need to set a .htaccess file to redirect to a specific URL only if the user came from outside. Once the request came from the same domain they must not be redirected. I'm not sure if it's possible?

#only from outside my_url.com
RedirectMatch 301 ^www.my_url.com$ my_url.com/home

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to use mod_rewrite (RewriteRule and RewriteCond) since you'll need to examine the Referer HTTP request header in order to determine that the request "came from another domain".

Note that checking the Referer header is not 100% reliable, since the Referer can be suppressed by the originating website and manipulated by the end user. (But it's all you've got.)

This should also be a 302 (temporary) redirect, otherwise a 301 (permanent) redirect will be cached by the browser and the user will be redirected again when following the internal link on your website.

I will assume that direct requests (ie. when the user types the URL into the browser) or requests where the Referer is suppressed should not be redirected. ie. they are treated like internal links.

You can do something like the following at the top of your root .htaccess file, where example.com is your website domain.

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www.)?example.com/ [NC]
RewriteRule !^path/to/specific-url.html$ /path/to/specific-url.html [R=302,L]

This states... for all requests, other than the specific-url.html, that are not directly typed into the browser (or Referer suppressed) and do not originate from your domain (example.com) then redirect to the specific-url.html.

Otherwise, any request for specific-url.html or originates from your domain, no redirect occurs.

If you've previously canonicalised the request (ie. HTTPS and www or non-www) then you could perhaps simplify the 2nd condition. Or updated this if you have other subdomains etc.

WARNING: This will badly affect SEO - if that is a concern - since search engines (eg. Googlebot) do not send a Referer header. You could potentially exclude bots by identifying the user-agent, however, you are then prone to being penalised for cloaking (serving different content to users and bots).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...