Rewrite URL based on HTTP_HOST

.htaccessmod-rewrite

Basically I want users can access the page via intranet and internet.

If users access the page via intranet, they can typing intranet IP of server on their browser address bar to 192.168.x.x.

But when users access the page via internet, they can typing public IP of server, I will rewrite the URL to public IP of server.

I have tried this, but I get the page not properly redirected.

RewriteEngine   On
RewriteBase     /mypath/
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteCond     %{HTTP_HOST}        !192.168.0.1
RewriteRule     ^(.*)$          http://<public.ip.of.server>/mypath/$1/ [L,R=301]
RewriteCond     %{HTTP_HOST}        !<public.ip.of.server>
RewriteRule     ^(.*)$          http://192.168.0.1/mypath/$1/   [L,R=301]

I have tried this too, but I get the page 500 internal server error.

<If "%{HTTP_HOST} == '192.168.0.1'">
RewriteEngine   On
RewriteBase     /mypath/
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://192.168.0.1/mypath/$1/   [L,R=301]
</If>
<If "%{HTTP_HOST} == 'public.ip.of.server'">
RewriteEngine   On
RewriteBase     /mypath/
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://<public.ip.of.server>/mypath/$1/ [L,R=301]
</If>

Am I doing something wrong?

Best Answer

I'm using Apache 2.2.3

The <If> Directive is part of Apache 2.4's core. Those directives will cause a 500 server error if you put them in 2.2. It's not clear at all what you're trying to do, but you can replace the <If> blocks with a simple RewriteCond.

The important concept here is that RewriteConds only apply to the immediately following RewriteRule directive, they won't apply to any other ones, only just that single one. So you need to duplicate conditions if you need them to be applied to multiple rules.

RewriteEngine   On
RewriteBase     /mypath/

RewriteCond     %{HTTP_HOST} ^192.168.0.1$
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://192.168.0.1/mypath/$1/   [L,R=301]

RewriteCond     %{HTTP_HOST} ^public.ip.of.server$
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://<public.ip.of.server>/mypath/$1/ [L,R=301]

But you can just get rid of all of that because you can redirect without using the http://hostname bit:

RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$  /mypath/$1/   [L,R=301]

And that would accomplish the above for any host.

Related Topic