Search code examples
apache.htaccessmod-rewrite

RewriteCond doesn't let my IP address through


I want to restrict access to my dev site to just my IP address. (eg 123.123.123.123)

I have the following in my .htaccess file. However I still get redirected to /dev_site_notice.html.

Am I specifying this correctly?

SetEnvIf X-Forwarded-Proto https HTTPS=on
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteCond %{REQUEST_URI} !/dev_site_notice.html$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
RewriteRule .* /dev_site_notice.html [R=302,L]

Solution

  • SetEnvIf X-Forwarded-Proto https HTTPS=on
    RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
    

    If you are checking for the X-Forwarded-Proto header in the SetEnvIf directive then it implies you are behind a proxy server (otherwise this directive should be removed). If this is the case then the REMOTE_ADDR server variable is the IP address of the proxy, not the client IP address.

    If (and only if) you are behind a proxy then you should be checking the X-Forwarded-For HTTP request header instead. For example:

    RewriteCond %{HTTP:X-Forwarded-For} !^123\.123\.123\.123($|\D)
    

    Note that the X-Forwarded-For header can contain multiple (comma-separated) IP addresses, depending on whether the request has gone through several proxies. The client-IP is usually first (left-most), but you may need to confirm this with the proxy. For this reason, the regex should not end with $ (not that your original regex did anyway), but rather ($|\D) (end-of-string OR not a digit).

    The X-Forwarded-For header is the defacto standard, but it can vary from proxy to proxy. It is the proxy server that sets this header, when the request passes through.