-1

I would like to make a redirect in Apache with a domain based rule. For example

If a user access to the page from example.com or another related page (example.com/another-url/), then redirect to example.com/page.html. Else, show the normal page.

I write in the .htaccess:

<IfModule mod_rewrite.c>    
    RewriteEngine on
    RewriteCond %{REMOTE_ADDR} !^example.com
    RewriteRule .* /page.html [R=302,L]    
</IfModule>

But it doesn't work.

MrWhite
  • 11,643
  • 4
  • 25
  • 40
  • "access to the page from `example.com`" - presumably you mean a request made **to** `example.com`? – MrWhite Mar 14 '17 at 21:23
  • 1
    Possible duplicate of [Redirect, Change URLs or Redirect HTTP to HTTPS in Apache - Everything You Ever Wanted to Know About Mod\_Rewrite Rules but Were Afraid to Ask](http://serverfault.com/questions/214512/redirect-change-urls-or-redirect-http-to-https-in-apache-everything-you-ever) – Jenny D Mar 21 '17 at 19:54

1 Answers1

2

Presumably you have multiple domains on this account?

To redirect either example.com/ or example.com/another-url/ to example.com/page.html then you can do something like the following in .htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(|another-url/)$ /page.html [R=302,L]

The HTTP_HOST server variable contains the host being requested. The pattern ^(|another-url/)$ matches either an empty URL-path (ie. the document root) or another-url/ (less the directory prefix).

RewriteCond %{REMOTE_ADDR} !^one.domain.com
RewriteRule .* /page.html [R=302,L]   

This would have redirected everything to /page.html. The problems with your original directives...

  • REMOTE_ADDR is the client IP address making the request, not the host being requested.
  • The ! prefix on the CondPattern negates the regex. So, in the above it matches when the REMOTE_ADDR is not example.com. (Always true.)
  • The .* RewriteRule pattern matches every URL!
MrWhite
  • 11,643
  • 4
  • 25
  • 40