wtfowned
wtfowned

Reputation: 124

Htaccess doesn't redirect request to php script

I have 2 vps :

  1. Centos 7 / Php 7.0 / Apache 2.4.6
  2. Ubuntu 18 / Php 7.2 / Apache 2.4.29

Both installed with VestaCP same config (apache as backend , nginx as frontend).

There are same script, which doesnt work on 2nd server.

.htaccess rule:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|png|gif)$ [NC]
RewriteCond %{REMOTE_ADDR} !^(127.0.0.1)$ [NC]
RewriteCond %{HTTP_USER_AGENT} (bad|useragents) [NC]
RewriteRule (.*) script.php?src=$1 [L]
</IfModule>

Note :

What it could be? I tried to debug apache logs, finding reason why request doesnt redirect, but apache LogLevel debug haven't shown any errors.

Upvotes: 1

Views: 232

Answers (1)

wtfowned
wtfowned

Reputation: 124

As @Phil said, the problem was in REMOTE_ADDR

On working server headers:

[HTTP_X_FORWARDED_FOR] => CLIENT_IP
[SERVER_NAME] => sitename.org
[SERVER_ADDR] => SERVER_IP
[SERVER_PORT] => 80
[REMOTE_ADDR] => CLIENT_IP

Not working server:

[HTTP_X_REAL_IP] => CLIENT_IP
[HTTP_X_FORWARDED_FOR] => CLIENT_IP
[SERVER_NAME] => sitename.org
[SERVER_ADDR] => SERVER_IP
[SERVER_PORT] => 80
[REMOTE_ADDR] => SERVER_IP

As you can see, "not working" server returns server IP for header SERVER_ADDR and REMOTE_ADDR.

So, to make it work, my code is :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|png|gif)$ [NC]
RewriteCond %{HTTP_X_REAL_IP} !^(127.0.0.1)$ [NC]
RewriteCond %{HTTP_USER_AGENT} (bad|useragents) [NC]
RewriteRule (.*) script.php?src=$1 [L]
</IfModule>

Now the question is - how to put clients IP in REMOTE_ADDR or better fix .htaccess and change it to HTTP_X_REAL_IP ? Which way is "the right way" ? I havent find fast solution, for now just changed htaccess to HTTP_X_REAL_IP.

Upvotes: 1

Related Questions