Apache “require ip” is not working when behind proxy. How to limit website access to IP when Apache is behind proxy.

I had a case where Apache did not respect the directives in .htaccess with ‘require ip‘ and I couldn’t limit the website to certain addresses. The problem is that when Apache is behind a proxy ( HAProxy in this case ), the ‘require ip‘ will not pass the correct IP address. The correct IP address of the visitor is located in the ‘X-Forwarded-For’ variable. Therefore, .htaccess needs to be modified so that instead of ‘require ip’, it will respect another variable into which we will pass the values of ‘X-Forwarded-For’.

Below is an example of how it was solved in a case where it was necessary to request a password only if the website visitor did not come from a specific IP address which is added to the exceptions.”

Example:

<If "%{HTTP_HOST} == 'this.isnowworking.com'">
SetEnv IF_MATCHES_HOST true
AuthUserFile /etc/httpd/.htpasswd
AuthType Basic
AuthName "Restricted access"

SetEnvIF X-Forwarded-For "1.1.1.1" AllowIP
SetEnvIF X-Forwarded-For "2.2.2.2" AllowIP
SetEnvIF X-Forwarded-For "3.3.3.3" AllowIP

<RequireAny>
Require valid-user
Require env AllowIP
</RequireAny>
</If>

Nice way to do HTTP to HTTPS redirection with Apache .htaccess

I had some sites on shared hosting environment for which I had to do http to https redirection with .htaccess file. I did 302 redirection intentionally so that in case of error, browser doesn’t cache redirection. You can aslo make permanent 301 redirect if needed.

This is nice and simple way to do it:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]

WordPress returning 404 Error on all subpages

In this case I used NGINX as reverse proxy for ssl offloading in front of Apache. On this WordPress installation I was getting 404 on all subpages. Htaccess syntax was correct as it was nginx configuration. In this case, problem was caused because of missing “AllowOverride” Apache directive which didn’t allow htaccess to be processed. I added “AllowOverride ALL” in apache configuration for this virtual host. Subpages started to work.

Example:

<VirtualHost *:8080>
DocumentRoot /var/www/mysite.com/
ServerName mysite.com
ServerAlias www.mysite.com

<Directory "/var/www/mysite.com/">
AllowOverride All
</Directory>
</VirtualHost>

© 2024 geegkytuts.net
Hosted by SIEL


About author