0

I need to redirect all users who don't have an 'allowed' IP-address to another subdomain. The users should be redirected to the other subdomain with the same URL.

For example:

  • dev.example.com/contact_us.php => www.example.com/contact_us.php

This part is now working with the following code in my .htaccess file:

RewriteCond %{REMOTE_ADDR} !^10\.0\.1\.1$
RewriteCond %{HTTP_HOST} ^dev\.example\.(.*)$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301,NE]

Besides that the domain can have different domain-extensions like: .com .net .pl .se

That means if the user try to navigate to dev.example.se/contact_us.php and don't have an 'allowed' IP-address - then the user should be redirected to www.example.se/contact_us.php

I can't figure out how to make the second part working.

anubhava
  • 761,203
  • 64
  • 569
  • 643
user3740970
  • 389
  • 1
  • 3
  • 16
  • 1
    As per [this meta post](https://meta.stackoverflow.com/questions/283057/mod-rewrite-questions-getting-migrated-to-sf) and [this meta post](https://meta.stackoverflow.com/questions/283033/are-htaccess-questions-ever-on-topic-at-so) this question is not at all off-topic for SO so close vote is wrong. This has been discussed again and again and it has been settled already that most of the rewrite rules are created and maintained by developers of the web applications/frameworks. – anubhava Nov 29 '20 at 10:54

1 Answers1

2

You can capture last of domain name from RewriteCond itself and use a back-reference later in RewriteRule like this:

RewriteEngine On

RewriteCond %{REMOTE_ADDR} !^10\.0\.1\.1$
RewriteCond %{HTTP_HOST} ^dev\.example\.(.+)$ [NC]
RewriteRule ^ https://www.example.%1%{REQUEST_URI} [L,R=301,NE]

Take note of capture group (.+) in RewriteCond that captured value after dev.example from host name. Then we use a back-reference of %1 later in RewriteRule that replaces same value.

Note that you may also use this rule where example is not repeated again:

RewriteCond %{REMOTE_ADDR} !^10\.0\.1\.1$
RewriteCond %{HTTP_HOST} ^dev\.(example\..+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301,NE]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • it seems like it is redirecting even if the IP-address IS listed as the 'allowed' IPs - do you know why? – user3740970 Nov 27 '20 at 12:56
  • This rule depends on `REMOTE_ADDR` variable. You can use a php script to print `REMOTE_ADDR`. Sometimes due to some proxy or gateway in between `REMOTE_ADDR` may carry different value – anubhava Nov 27 '20 at 12:58