简体   繁体   中英

.htaccess | Too many redirects

I want to add a IP filter into my .htaccess file, but after I applied it, a too many redirects error will show.

Content of .htaccess :

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} on

RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx
RewriteRule ^ /test.php [R=302,L]

Why am I getting this error?

I'm assuming that you are trying to do two things here:

  1. Force HTTPS and www.
  2. Redirect to test.php if a certain IP is making the request

The issue you were facing was due to the fact that even though the IP address was being matched, it was still being checked for when reaching test.php . As there would be a match again, the redirect would loop continuously. By adding the appropriate condition, we check to see that the requested URI is not test.php before checking the IP addresses. The line in question is shown near the bottom of my answer, which includes enhancements to your original code.

RewriteEngine on

# Force HTTPS
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# Force www
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]

# Redirect to test.php if a certain IP is matched
RewriteCond %{REQUEST_URI} !^/test\.php
RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx
RewriteRule ^ /test.php [R=302,L]

If you need to match multiple IP addresses, then you should make use of the OR flag for every IP address except the last one:

# Redirect to test.php if a certain set of IPs are matched
RewriteCond %{REQUEST_URI} !^/test\.php
RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx [OR]
RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx [OR]
RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx [OR]
RewriteCond %{REMOTE_ADDR} xxx.xxx.xxx.xxx
RewriteRule ^ /test.php [R=302,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM